The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: drop the bundled-hindsight tests, retarget the generic ones
teknium1090b06c345c3
diff --git a/tests/agent/test_memory_session_switch.py b/tests/agent/test_memory_session_switch.pyindex 2156ee475c0..b4f913d4bf3 100644--- a/tests/agent/test_memory_session_switch.py+++ b/tests/agent/test_memory_session_switch.py@@ -139,111 +139,3 @@ def test_manager_isolates_provider_failures():# ---------------------------------------------------------------------------# MemoryManager.sync_all / queue_prefetch_all — session_id propagation# ----------------------------------------------------------------------------------# ----------------------------------------------------------------------------# Hindsight reference implementation — state-flush semantics-# ------------------------------------------------------------------------------def _make_hindsight_provider():- """Build a bare HindsightMemoryProvider that skips network setup.-- We instantiate without importing optional deps at class-level by- bypassing __init__ and seeding the attributes on_session_switch- reads/writes. This keeps the test hermetic.- """- import threading- hindsight_mod = pytest.importorskip("plugins.memory.hindsight")- provider = object.__new__(hindsight_mod.HindsightMemoryProvider)- provider._session_id = "old-sid"- provider._parent_session_id = ""- provider._document_id = "old-sid-20260101_000000_000000"- provider._session_turns = ["turn-1", "turn-2"]- provider._turn_counter = 2- provider._turn_index = 2- # Attrs read by _build_metadata / _build_retain_kwargs when the- # buffer-flush path on session switch fires. Empty strings keep the- # metadata minimal but well-formed.- provider._retain_source = ""- provider._platform = ""- provider._user_id = ""- provider._user_name = ""- provider._chat_id = ""- provider._chat_name = ""- provider._chat_type = ""- provider._thread_id = ""- provider._agent_identity = ""- provider._agent_workspace = ""- provider._retain_tags = []- provider._retain_context = "test-context"- provider._retain_async = False- provider._bank_id = "test-bank"- # Prefetch state the switch path drains/clears.- provider._prefetch_thread = None- provider._prefetch_lock = threading.Lock()- provider._prefetch_result = ""- # Sync thread tracking (legacy alias at the writer).- provider._sync_thread = None- # Writer queue infra the flush-on-switch path enqueues onto. We stub- # _ensure_writer / _register_atexit so no real thread is spawned;- # tests exercising flush delivery live in- # tests/plugins/memory/test_hindsight_provider.py where the full- # writer-queue wiring is in place.- import queue as _queue- provider._retain_queue = _queue.Queue()- provider._shutting_down = threading.Event()- provider._atexit_registered = True- provider._ensure_writer = lambda: None- provider._register_atexit = lambda: None- # Mode + API state used by _resolve_retain_target; stub the resolver- # so tests don't actually probe the API. Real probe behavior is- # exercised by tests in tests/plugins/memory/test_hindsight_provider.py.- provider._mode = "cloud"- provider._api_url = ""- provider._api_key = ""- provider._client = None- provider._resolve_retain_target = lambda fb: (fb, None)- # Stub the network-touching helper so any enqueued flush closure is- # a no-op if ever drained in a unit test.- provider._run_hindsight_operation = lambda _op: None- return provider---def test_hindsight_on_session_switch_updates_session_id_and_mints_fresh_doc():- provider = _make_hindsight_provider()- old_doc = provider._document_id-- provider.on_session_switch(- "new-sid", parent_session_id="old-sid", reset=False, reason="resume"- )-- assert provider._session_id == "new-sid"- assert provider._parent_session_id == "old-sid"- # Document id MUST be fresh — else next retain overwrites old session doc- assert provider._document_id != old_doc- assert provider._document_id.startswith("new-sid-")---def test_hindsight_on_session_switch_clears_turn_buffers():- """Accumulated _session_turns must not leak into the next session.-- Hindsight batches turns under a single _document_id. If the buffer- isn't cleared on switch, the next retain under the new _document_id- flushes turns that belong to the previous session.- """- provider = _make_hindsight_provider()- provider.on_session_switch("new-sid", parent_session_id="old-sid")- assert provider._session_turns == []- assert provider._turn_counter == 0- assert provider._turn_index == 0------diff --git a/tests/hermes_cli/test_web_server.py b/tests/hermes_cli/test_web_server.pyindex 0256d3da659..a8cb9cd890f 100644--- a/tests/hermes_cli/test_web_server.py+++ b/tests/hermes_cli/test_web_server.py@@ -894,26 +894,93 @@ class TestWebServerEndpoints:+ # A user-installed memory provider with a DECLARED config surface (``config_schema.py``, flat+ # ``<home>/<name>/config.json`` storage) and a live ``get_config_schema``/``save_config`` pair.+ # Bundled providers no longer ship a flat-storage declared schema (hindsight moved to the+ # plugin catalog), so the generic router paths are exercised against this synthetic one.+ _FLATPROV_INIT = """+import json+from pathlib import Path+from agent.memory_provider import MemoryProvider+++class FlatProvMemoryProvider(MemoryProvider):+ @property+ def name(self):+ return "flatprov"++ def is_available(self):+ return True++ def initialize(self, session_id, **kwargs):+ pass++ def get_tool_schemas(self):+ return []++ def get_config_schema(self):+ return [+ {"key": "mode", "label": "Mode", "choices": ["cloud", "local_external"], "default": "cloud"},+ {"key": "api_url", "label": "API URL", "default": ""},+ {"key": "api_key", "label": "API key", "secret": True, "env_var": "FLATPROV_API_KEY"},+ {"key": "bank_id", "label": "Bank", "default": "hermes"},+ {"key": "recall_budget", "label": "Budget", "choices": ["low", "mid", "high"], "default": "mid"},+ ]++ def save_config(self, values, hermes_home):+ path = Path(hermes_home) / "flatprov" / "config.json"+ path.parent.mkdir(parents=True, exist_ok=True)+ existing = json.loads(path.read_text()) if path.exists() else {}+ existing.update(values)+ path.write_text(json.dumps(existing))+"""+ _FLATPROV_SCHEMA = """+from plugins.memory.config_schema import (+ KIND_SECRET, KIND_SELECT, KIND_TEXT, ProviderConfigSchema, ProviderField, ProviderFieldOption,+)++CONFIG_SCHEMA = ProviderConfigSchema(+ name="flatprov",+ label="Flat Provider",+ fields=(+ ProviderField(key="mode", label="Mode", kind=KIND_SELECT, description="", default="cloud",+ options=(ProviderFieldOption("cloud", "Cloud"), ProviderFieldOption("local_external", "Local"))),+ ProviderField(key="api_url", label="API URL", kind=KIND_TEXT, description=""),+ ProviderField(key="api_key", label="API key", kind=KIND_SECRET, description="", env_key="FLATPROV_API_KEY"),+ ),+)+"""++ def _install_flatprov(self):+ from hermes_constants import get_hermes_home++ plugin_dir = get_hermes_home() / "plugins" / "flatprov"+ plugin_dir.mkdir(parents=True, exist_ok=True)+ (plugin_dir / "__init__.py").write_text(self._FLATPROV_INIT, encoding="utf-8")+ (plugin_dir / "config_schema.py").write_text(self._FLATPROV_SCHEMA, encoding="utf-8")+ return plugin_dir+def test_declared_surface_put_writes_config_and_secret(self):from hermes_constants import get_hermes_homefrom hermes_cli.config import load_env+ self._install_flatprov()resp = self.client.put(- "/api/memory/providers/hindsight/config?surface=declared",+ "/api/memory/providers/flatprov/config?surface=declared",json={"values": {"mode": "local_external","api_url": "http://localhost:8888",- "api_key": "hs-declared-key",+ "api_key": "fp-declared-key",}},)assert resp.status_code == 200assert resp.json() == {"ok": True}- assert load_env()["HINDSIGHT_API_KEY"] == "hs-declared-key"+ assert load_env()["FLATPROV_API_KEY"] == "fp-declared-key"- config_path = get_hermes_home() / "hindsight" / "config.json"+ config_path = get_hermes_home() / "flatprov" / "config.json"provider_config = json.loads(config_path.read_text(encoding="utf-8"))assert provider_config["mode"] == "local_external"assert provider_config["api_url"] == "http://localhost:8888"@@ -976,13 +1043,14 @@ class TestWebServerEndpoints:from hermes_constants import get_hermes_homefrom hermes_cli.config import load_config, load_env+ self._install_flatprov()resp = self.client.put(- "/api/memory/providers/hindsight/config",+ "/api/memory/providers/flatprov/config",json={"values": {"mode": "local_external","api_url": "http://localhost:8888",- "api_key": "hs-test-key",+ "api_key": "fp-test-key","bank_id": "ben-bank","recall_budget": "high",}@@ -990,11 +1058,11 @@ class TestWebServerEndpoints:)assert resp.status_code == 200- assert resp.json() == {"ok": True, "active": "hindsight"}- assert load_config()["memory"]["provider"] == "hindsight"- assert load_env()["HINDSIGHT_API_KEY"] == "hs-test-key"+ assert resp.json() == {"ok": True, "active": "flatprov"}+ assert load_config()["memory"]["provider"] == "flatprov"+ assert load_env()["FLATPROV_API_KEY"] == "fp-test-key"- config_path = get_hermes_home() / "hindsight" / "config.json"+ config_path = get_hermes_home() / "flatprov" / "config.json"provider_config = json.loads(config_path.read_text(encoding="utf-8"))assert provider_config["mode"] == "local_external"assert provider_config["api_url"] == "http://localhost:8888"@@ -1004,12 +1072,13 @@ class TestWebServerEndpoints:def test_get_memory_provider_config_does_not_return_secret(self):+ self._install_flatprov()self.client.put(- "/api/memory/providers/hindsight/config",+ "/api/memory/providers/flatprov/config",json={"values": {"mode": "cloud",- "api_url": "https://api.hindsight.vectorize.io",+ "api_url": "https://api.example.invalid","api_key": "secret-value","bank_id": "hermes","recall_budget": "mid",@@ -1017,7 +1086,7 @@ class TestWebServerEndpoints:},)- resp = self.client.get("/api/memory/providers/hindsight/config")+ resp = self.client.get("/api/memory/providers/flatprov/config")assert resp.status_code == 200data = resp.json()@@ -2818,7 +2887,7 @@ class TestBuildSchemaFromConfig:monkeypatch.setattr(_web_server_config,"_memory_provider_options",- lambda: ["", "honcho", "hindsight", "freshly_installed"],+ lambda: ["", "honcho", "mem0", "freshly_installed"],)fields = _web_server_config._schema_with_dynamic_provider_options()diff --git a/tests/plugins/memory/test_bom_tolerant_config_reads.py b/tests/plugins/memory/test_bom_tolerant_config_reads.pyindex 93925a4fd87..6f0868a255f 100644--- a/tests/plugins/memory/test_bom_tolerant_config_reads.py+++ b/tests/plugins/memory/test_bom_tolerant_config_reads.py@@ -2,7 +2,7 @@Notepad and PowerShell ``>`` prepend U+FEFF when saving; ``json.loads`` rejects it("Unexpected UTF-8 BOM") and every loader below degrades to defaults, so a user who-edited mem0.json / honcho.json / hindsight config.json / supermemory.json lost the+edited mem0.json / honcho.json / supermemory.json lost thewhole config with no error (Qwen CLI creds raised ``qwen_auth_read_failed``). Sameclass as the auth-store/.env sweep; these were the missed sibling readers."""@@ -20,7 +20,7 @@ def _write_bom_json(path: Path, payload: dict) -> Path:def _via_shared_reader(p: Path, monkeypatch) -> dict:- from utils import read_json_or_empty # mem0 / hindsight / honcho CLI all read through this+ from utils import read_json_or_empty # mem0 / honcho CLI all read through thisreturn read_json_or_empty(p)@@ -29,13 +29,6 @@ def _via_supermemory(p: Path, monkeypatch) -> dict:return _load_supermemory_config(str(p.parent))-def _via_hindsight_runtime_deps(p: Path, monkeypatch) -> dict:- import hermes_cli.memory_setup as ms- monkeypatch.setattr(ms, "get_hermes_home", lambda: p.parent.parent) # <home>/hindsight/config.json- deps = ms._provider_pip_dependencies("hindsight", ["hindsight-client"])- return {"workspace": "bom-ws" if "hindsight-all" in deps else None, "container_tag": None}--def _via_honcho_client(p: Path, monkeypatch) -> dict:from plugins.memory.honcho.client import HonchoClientConfigcfg = HonchoClientConfig.from_global_config(config_path=p)@@ -46,7 +39,6 @@ def _via_honcho_client(p: Path, monkeypatch) -> dict:("mem0.json", _via_shared_reader),("supermemory.json", _via_supermemory),("honcho.json", _via_honcho_client),- ("hindsight/config.json", _via_hindsight_runtime_deps),])def test_plugin_config_json_tolerates_bom(tmp_path, monkeypatch, filename, loader):target = tmp_path / filenamediff --git a/tests/plugins/memory/test_hindsight_config_schema.py b/tests/plugins/memory/test_hindsight_config_schema.pydeleted file mode 100644index a521ee5d2d3..00000000000--- a/tests/plugins/memory/test_hindsight_config_schema.py+++ /dev/null@@ -1,51 +0,0 @@-"""Tests for Hindsight's declared config surface."""--from plugins.memory.config_schema import (- KIND_SECRET,- KIND_SELECT,- get_provider_config_schema,-)---def test_hindsight_is_declared():- provider = get_provider_config_schema("hindsight")-- assert provider is not None- assert provider.label == "Hindsight"- assert {field.key for field in provider.fields} == {- "mode",- "api_key",- "api_url",- "bank_id",- "recall_budget",- }---def test_fields_are_all_inline():- provider = get_provider_config_schema("hindsight")- assert provider is not None-- # Hindsight is simple enough to render fully in the compact panel, so it- # never grows a Full config… modal.- assert all(field.inline for field in provider.fields)---def test_mode_gating_is_expressed_as_select_options():- provider = get_provider_config_schema("hindsight")- assert provider is not None-- mode = next(field for field in provider.fields if field.key == "mode")- assert mode.kind == KIND_SELECT- assert mode.allowed_values() == {"cloud", "local_external"}- # local_embedded is intentionally unsupported on desktop.- assert "local_embedded" not in mode.allowed_values()---def test_api_key_is_a_secret_bound_to_env():- provider = get_provider_config_schema("hindsight")- assert provider is not None-- api_key = next(field for field in provider.fields if field.key == "api_key")- assert api_key.kind == KIND_SECRET- assert api_key.is_secret is True- assert api_key.env_key == "HINDSIGHT_API_KEY"diff --git a/tests/plugins/memory/test_hindsight_env_perms.py b/tests/plugins/memory/test_hindsight_env_perms.pydeleted file mode 100644index f956106c854..00000000000--- a/tests/plugins/memory/test_hindsight_env_perms.py+++ /dev/null@@ -1,145 +0,0 @@-"""Regression tests: the embedded Hindsight profile env file carries the-plaintext ``HINDSIGHT_API_LLM_API_KEY`` and must be created/kept owner-only-(0600), and must not survive a failed post-write permission validation.-"""--import os-import stat-from pathlib import Path--import pytest--from plugins.memory.hindsight import (- _embedded_profile_env_path,- _materialize_embedded_profile_env,-)-from plugins.memory.hindsight.embedded import _build_embedded_profile_env, _may_rewrite_profile_env--[email protected](autouse=True)-def _isolated_home(tmp_path, monkeypatch):- isolated_home = tmp_path / "user-home"- monkeypatch.setattr(Path, "home", classmethod(lambda cls: isolated_home))- return isolated_home---_CONFIG = {- "profile": "hermes",- "llm_provider": "openai",- "llm_model": "gpt-4o-mini",-}--[email protected](os.name == "nt", reason="POSIX mode bits are not enforced on Windows")-def test_fresh_profile_env_is_owner_only_despite_permissive_umask():- old_umask = os.umask(0o022)- try:- profile_env = _materialize_embedded_profile_env(- _CONFIG, llm_api_key="sk-hindsight-secret"- )- finally:- os.umask(old_umask)-- assert profile_env.exists()- assert stat.S_IMODE(profile_env.stat().st_mode) == 0o600- assert "HINDSIGHT_API_LLM_API_KEY=sk-hindsight-secret\n" in profile_env.read_text(- encoding="utf-8"- )--[email protected](os.name == "nt", reason="POSIX mode bits are not enforced on Windows")-def test_rewrite_tightens_existing_world_readable_profile_env():- profile_env = _embedded_profile_env_path(_CONFIG)- profile_env.parent.mkdir(parents=True)- profile_env.write_text("HINDSIGHT_API_LLM_API_KEY=stale\n", encoding="utf-8")- os.chmod(profile_env, 0o644)-- _materialize_embedded_profile_env(_CONFIG, llm_api_key="sk-current")-- assert stat.S_IMODE(profile_env.stat().st_mode) == 0o600- assert "HINDSIGHT_API_LLM_API_KEY=sk-current\n" in profile_env.read_text(- encoding="utf-8"- )--[email protected](os.name == "nt", reason="POSIX mode bits are not enforced on Windows")-def test_secret_file_removed_when_permission_validation_fails(monkeypatch):- """If the post-write permission check cannot verify 0600, the plaintext- key file must not be left behind."""- import plugins.memory.hindsight.embedded as hs_embedded-- def _fail_validation(profile_env):- raise PermissionError(f"not owner-only: {profile_env}")-- monkeypatch.setattr(hs_embedded, "_validate_profile_env_permissions", _fail_validation)-- with pytest.raises(PermissionError):- _materialize_embedded_profile_env(_CONFIG, llm_api_key="sk-doomed")-- assert not _embedded_profile_env_path(_CONFIG).exists(), (- "secret env file must be cleaned up when validation fails"- )--[email protected](os.name == "nt", reason="POSIX mode bits are not enforced on Windows")-def test_scopeless_worker_reuses_on_disk_key(monkeypatch):- """Durability core: with no secret scope, the key resolves from disk.-- The daemon-start worker usually has no scope; without the disk fallback- the client would be built keyless and the upstream manager merge- (ensure_running -> _register_profile -> create_profile rewrite) would- overwrite the file's good key with emptiness.- """- from agent import secret_scope-- profile_env = _embedded_profile_env_path(_CONFIG)- profile_env.parent.mkdir(parents=True)- profile_env.write_text(- "HINDSIGHT_API_LLM_PROVIDER=openai\n"- "HINDSIGHT_API_LLM_API_KEY=sk-test-live-key\n"- "HINDSIGHT_API_LLM_MODEL=gpt-4o-mini\n"- "HINDSIGHT_API_LOG_LEVEL=info\n",- encoding="utf-8",- )- os.chmod(profile_env, 0o600)-- token = secret_scope.set_secret_scope(None)- monkeypatch.setattr(secret_scope, "_MULTIPLEX_ACTIVE", True)- monkeypatch.delenv("HINDSIGHT_API_LLM_API_KEY", raising=False)- try:- from plugins.memory.hindsight.embedded import _embedded_llm_api_key-- assert _embedded_llm_api_key(_CONFIG) == "sk-test-live-key"- # ...so the build carries a key and the rewrite gate passes.- assert _build_embedded_profile_env(_CONFIG)["HINDSIGHT_API_LLM_API_KEY"] == "sk-test-live-key"- assert _may_rewrite_profile_env(_CONFIG) is True- finally:- secret_scope.reset_secret_scope(token)-----def test_rewrite_allowed_when_build_carries_key():- """A build WITH key material (rotation, model drift) must still rewrite."""- profile_env = _embedded_profile_env_path(_CONFIG)- profile_env.parent.mkdir(parents=True)- profile_env.write_text("HINDSIGHT_API_LLM_API_KEY=sk-old\n", encoding="utf-8")-- cfg = dict(_CONFIG, llm_api_key="sk-new")- assert _may_rewrite_profile_env(cfg) is True- _materialize_embedded_profile_env(cfg)- assert "HINDSIGHT_API_LLM_API_KEY=sk-new\n" in profile_env.read_text(encoding="utf-8")---def test_api_prefixed_vault_name_resolves(monkeypatch):- """The vault item is HINDSIGHT_API_LLM_API_KEY; the wizard name alone misses."""- from agent import secret_scope- import plugins.memory.hindsight.embedded as hs_embedded-- token = secret_scope.set_secret_scope({"HINDSIGHT_API_LLM_API_KEY": "sk-test-live-key"})- monkeypatch.delenv("HINDSIGHT_LLM_API_KEY", raising=False)- monkeypatch.delenv("HINDSIGHT_API_LLM_API_KEY", raising=False)- try:- assert hs_embedded._embedded_llm_api_key(_CONFIG) == "sk-test-live-key"- finally:- secret_scope.reset_secret_scope(token)diff --git a/tests/plugins/memory/test_hindsight_local_runtime_hint.py b/tests/plugins/memory/test_hindsight_local_runtime_hint.pydeleted file mode 100644index 075cb38e3a4..00000000000--- a/tests/plugins/memory/test_hindsight_local_runtime_hint.py+++ /dev/null@@ -1,56 +0,0 @@-"""NousResearch/hermes-agent#7718 — actionable message when local_embedded-runtime (`hindsight-all`) is missing.--`local_embedded` imports `from hindsight import HindsightEmbedded`, provided-only by `hindsight-all`. When it's absent the provider disables itself; the-disable warning should point the user at the fix rather than just echoing-`No module named 'hindsight'`.-"""--import sys--import plugins.memory.hindsight as hs-from plugins.memory.hindsight import HindsightMemoryProvider, _local_runtime_hint---def test_hint_for_missing_hindsight_all():- hint = _local_runtime_hint("No module named 'hindsight'")- assert "hindsight-all" in hint- assert "hermes memory setup" in hint- assert sys.executable in hint---def test_hint_for_missing_hindsight_embed():- hint = _local_runtime_hint("No module named 'hindsight_embed.daemon_embed_manager'")- assert "hindsight-all" in hint---def test_no_hint_for_unrelated_runtime_error():- # e.g. the NumPy-on-old-CPU failure _check_local_runtime also guards against- assert _local_runtime_hint("Illegal instruction (NumPy SIMD)") == ""- assert _local_runtime_hint(None) == ""---# unavailable_reason() — surfaces the hint through the reachable path (#7718):-# is_available() gates initialize() out, so the hint must come from here.---def test_unavailable_reason_surfaces_hint_for_local_embedded(monkeypatch):- monkeypatch.setattr(hs, "_load_config", lambda: {"mode": "local_embedded"})- monkeypatch.setattr(hs, "_check_local_runtime", lambda: (False, "No module named 'hindsight'"))- reason = HindsightMemoryProvider().unavailable_reason()- assert "hindsight-all" in reason- assert reason == reason.strip() # no leading/trailing whitespace---def test_unavailable_reason_empty_for_cloud(monkeypatch):- monkeypatch.setattr(hs, "_load_config", lambda: {"mode": "cloud"})- # Should not even probe the runtime for a cloud provider.- monkeypatch.setattr(hs, "_check_local_runtime", lambda: (_ for _ in ()).throw(AssertionError("probed")))- assert HindsightMemoryProvider().unavailable_reason() == ""---def test_unavailable_reason_empty_when_runtime_present(monkeypatch):- monkeypatch.setattr(hs, "_load_config", lambda: {"mode": "local_embedded"})- monkeypatch.setattr(hs, "_check_local_runtime", lambda: (True, None))- assert HindsightMemoryProvider().unavailable_reason() == ""diff --git a/tests/plugins/memory/test_hindsight_provider.py b/tests/plugins/memory/test_hindsight_provider.pydeleted file mode 100644index 93a429464e5..00000000000--- a/tests/plugins/memory/test_hindsight_provider.py+++ /dev/null@@ -1,1779 +0,0 @@-"""Tests for the Hindsight memory provider plugin.--Tests cover config loading, tool handlers (tags, max_tokens, types),-prefetch (auto_recall, preamble, query truncation), sync_turn (auto_retain,-turn counting, tags), and schema completeness.-"""--import importlib.util-import json-import os-import re-import stat-import sys-import threading-import time-from datetime import datetime-from pathlib import Path-from types import ModuleType, SimpleNamespace-from unittest.mock import AsyncMock, MagicMock-from zoneinfo import ZoneInfo--import pytest--from hermes_cli.memory_setup import _CANCELLED-from plugins.memory.hindsight import (- HindsightMemoryProvider,- RECALL_SCHEMA,- REFLECT_SCHEMA,- RETAIN_SCHEMA,- _load_config,- _load_simple_env,- _build_embedded_profile_env,- _normalize_observation_scopes,- _normalize_retain_tags,- _resolve_bank_id_template,- _WRITER_SENTINEL,-)-from plugins.memory.hindsight.settings import _sanitize_bank_segment---# ----------------------------------------------------------------------------# Fixtures-# -----------------------------------------------------------------------------[email protected](autouse=True)-def _clean_env(tmp_path, monkeypatch):- """Ensure no stale env vars or Windows home state leak between tests."""- for key in (- "HINDSIGHT_API_KEY", "HINDSIGHT_API_URL", "HINDSIGHT_BANK_ID",- "HINDSIGHT_BUDGET", "HINDSIGHT_MODE", "HINDSIGHT_TIMEOUT",- "HINDSIGHT_IDLE_TIMEOUT", "HINDSIGHT_LLM_API_KEY",- "HINDSIGHT_RETAIN_TAGS", "HINDSIGHT_RETAIN_OBSERVATION_SCOPES",- "HINDSIGHT_RETAIN_SOURCE",- "HINDSIGHT_RETAIN_USER_PREFIX", "HINDSIGHT_RETAIN_ASSISTANT_PREFIX",- ):- monkeypatch.delenv(key, raising=False)-- # On Windows pathlib.Path.home() resolves USERPROFILE/HOMEDRIVE+HOMEPATH,- # not the POSIX HOME alias that these tests historically monkeypatched.- # Patch the actual API and keep all legacy profile writes in tmp_path.- isolated_home = tmp_path / "user-home"- monkeypatch.setattr(Path, "home", classmethod(lambda cls: isolated_home))-- # These tests provide client doubles, so they must not attempt a network- # install merely because the optional SDK is absent from the test env.- monkeypatch.setattr("tools.lazy_deps.ensure", lambda *args, **kwargs: None)-- # The retain-operation path imports this exception solely to classify a- # fake client's response. Supply the smallest matching SDK surface so the- # mocked tests remain runnable without the optional Hindsight extra.- # Only when the real SDK is absent: shadowing an installed SDK with a- # fake (no ``__path__``) breaks ``import hindsight_client`` and turns the- # pinned-client test into a permanent skip.- if importlib.util.find_spec("hindsight_client_api") is not None:- return- client_api = ModuleType("hindsight_client_api")- exceptions = ModuleType("hindsight_client_api.exceptions")-- class NotFoundException(Exception):- def __init__(self, *args, **kwargs):- super().__init__(*args)-- exceptions.NotFoundException = NotFoundException- client_api.exceptions = exceptions- monkeypatch.setitem(sys.modules, "hindsight_client_api", client_api)- monkeypatch.setitem(sys.modules, "hindsight_client_api.exceptions", exceptions)---def _make_mock_client():- """Create a mock Hindsight client with async methods."""- async def _aretain(- bank_id,- content,- timestamp=None,- context=None,- document_id=None,- metadata=None,- entities=None,- tags=None,- update_mode=None,- retain_async=None,- ):- return SimpleNamespace(ok=True)-- client = MagicMock()- client.aretain = AsyncMock(side_effect=_aretain)- client.arecall = AsyncMock(- return_value=SimpleNamespace(- results=[- SimpleNamespace(text="Memory 1"),- SimpleNamespace(text="Memory 2"),- ]- )- )- client.areflect = AsyncMock(- return_value=SimpleNamespace(text="Synthesized answer")- )- client.aretain_batch = AsyncMock()- client.aclose = AsyncMock()- return client---def _provider_for_mode(tmp_path, monkeypatch, mode: str):- """Create an initialized provider without pre-seeding its client."""- config = {- "mode": mode,- "apiKey": "test-key",- "api_url": "http://localhost:9999",- "bank_id": "test-bank",- "budget": "mid",- "memory_mode": "hybrid",- }- config_path = tmp_path / "hindsight" / "config.json"- config_path.parent.mkdir(parents=True, exist_ok=True)- config_path.write_text(json.dumps(config))-- monkeypatch.setattr(- "plugins.memory.hindsight.get_hermes_home", lambda: tmp_path- )-- provider = HindsightMemoryProvider()- provider.initialize(session_id="test-session", hermes_home=str(tmp_path), platform="cli")- return provider---def _assert_cloud_client_lazy_installed_before_import(tmp_path, monkeypatch, mode: str):- """Cloud/local-external clients must ensure lazy deps before importing."""- import builtins-- provider = _provider_for_mode(tmp_path, monkeypatch, mode)- ensure_calls = []-- def fake_ensure(feature, prompt=True):- ensure_calls.append((feature, prompt))-- class FakeHindsight:- def __init__(self, **kwargs):- self.kwargs = kwargs-- real_import = builtins.__import__-- def guarded_import(name, globals=None, locals=None, fromlist=(), level=0):- if name == "hindsight_client":- if ensure_calls != [("memory.hindsight", False)]:- raise ModuleNotFoundError("No module named 'hindsight_client'")- return SimpleNamespace(Hindsight=FakeHindsight)- return real_import(name, globals, locals, fromlist, level)-- monkeypatch.setattr("tools.lazy_deps.ensure", fake_ensure)- monkeypatch.setattr(builtins, "__import__", guarded_import)-- client = provider._get_client()-- assert ensure_calls == [("memory.hindsight", False)]- assert isinstance(client, FakeHindsight)- assert client.kwargs == {- "base_url": "http://localhost:9999",- "timeout": 120.0,- "api_key": "test-key",- }---class _FakeSessionDB:- def __init__(self, messages=None):- self._messages = list(messages or [])-- def get_messages_as_conversation(self, session_id):- return list(self._messages)---def provider(tmp_path, monkeypatch):- """Create an initialized HindsightMemoryProvider with a mock client."""- config = {- "mode": "cloud",- "apiKey": "test-key",- "api_url": "http://localhost:9999",- "bank_id": "test-bank",- "budget": "mid",- "memory_mode": "hybrid",- }- config_path = tmp_path / "hindsight" / "config.json"- config_path.parent.mkdir(parents=True, exist_ok=True)- config_path.write_text(json.dumps(config))-- monkeypatch.setattr(- "plugins.memory.hindsight.get_hermes_home", lambda: tmp_path- )-- p = HindsightMemoryProvider()- p.initialize(session_id="test-session", hermes_home=str(tmp_path), platform="cli")- p._client = _make_mock_client()- return p---def provider_with_config(tmp_path, monkeypatch):- """Create a provider factory that accepts custom config overrides."""- def _make(**overrides):- config = {- "mode": "cloud",- "apiKey": "test-key",- "api_url": "http://localhost:9999",- "bank_id": "test-bank",- "budget": "mid",- "memory_mode": "hybrid",- }- config.update(overrides)- config_path = tmp_path / "hindsight" / "config.json"- config_path.parent.mkdir(parents=True, exist_ok=True)- config_path.write_text(json.dumps(config))-- monkeypatch.setattr(- "plugins.memory.hindsight.get_hermes_home", lambda: tmp_path- )-- p = HindsightMemoryProvider()- p.initialize(session_id="test-session", hermes_home=str(tmp_path), platform="cli")- p._client = _make_mock_client()- return p- return _make---def test_normalize_retain_tags_accepts_csv_and_dedupes():- assert _normalize_retain_tags("agent:fakeassistantname, source_system:hermes-agent, agent:fakeassistantname") == [- "agent:fakeassistantname",- "source_system:hermes-agent",- ]---# ----------------------------------------------------------------------------# Schema tests-# ------------------------------------------------------------------------------class TestSchemas:- def test_retain_schema_has_content(self):- assert RETAIN_SCHEMA["name"] == "hindsight_retain"- assert "content" in RETAIN_SCHEMA["parameters"]["properties"]- assert "tags" in RETAIN_SCHEMA["parameters"]["properties"]- assert "content" in RETAIN_SCHEMA["parameters"]["required"]--- def test_get_tool_schemas_returns_three(self, provider):- schemas = provider.get_tool_schemas()- assert len(schemas) == 3- names = {s["name"] for s in schemas}- assert names == {"hindsight_retain", "hindsight_recall", "hindsight_reflect"}-- def test_context_mode_returns_no_tools(self, provider_with_config):- p = provider_with_config(memory_mode="context")- assert p.get_tool_schemas() == []---# ----------------------------------------------------------------------------# Config tests-# ------------------------------------------------------------------------------class TestConfig:- def test_cloud_client_lazy_installs_dependency_before_import(self, tmp_path, monkeypatch):- _assert_cloud_client_lazy_installed_before_import(tmp_path, monkeypatch, "cloud")--- def test_default_values(self, provider):- assert provider._auto_retain is True- assert provider._auto_recall is True- assert provider._retain_every_n_turns == 1- assert provider._recall_max_tokens == 4096- assert provider._recall_max_input_chars == 800- assert provider._tags is None- assert provider._observation_scopes is None- assert provider._recall_tags is None- # Default recall narrowed to observation-only; world/experience are- # aggregate facts that often crowd out concrete-event signal during- # auto-recall. Users opt back in via the recall_types config key.- assert provider._recall_types == ["observation"]- assert provider._bank_mission == ""- assert provider._bank_retain_mission is None- assert provider._retain_context == "conversation between Hermes Agent and the User"-- def test_recall_types_default_is_observation_only(self, provider):- """Auto-recall must filter to observation by default."""- assert provider._recall_types == ["observation"]--- def test_observation_scopes_keyword_config(self, provider_with_config):- p = provider_with_config(observation_scopes="per_tag")- assert p._observation_scopes == "per_tag"--- def test_custom_config_values(self, provider_with_config):- p = provider_with_config(- retain_tags=["tag1", "tag2"],- retain_source="hermes",- retain_user_prefix="User (fakeusername)",- retain_assistant_prefix="Assistant (fakeassistantname)",- recall_tags=["recall-tag"],- recall_tags_match="all",- auto_retain=False,- auto_recall=False,- retain_every_n_turns=3,- retain_context="custom-ctx",- bank_retain_mission="Extract key facts",- recall_max_tokens=2048,- recall_types=["world", "experience"],- recall_prompt_preamble="Custom preamble:",- recall_max_input_chars=500,- bank_mission="Test agent mission",- )- assert p._tags == ["tag1", "tag2"]- assert p._retain_tags == ["tag1", "tag2"]- assert p._retain_source == "hermes"- assert p._retain_user_prefix == "User (fakeusername)"- assert p._retain_assistant_prefix == "Assistant (fakeassistantname)"- assert p._recall_tags == ["recall-tag"]- assert p._recall_tags_match == "all"- assert p._auto_retain is False- assert p._auto_recall is False- assert p._retain_every_n_turns == 3- assert p._retain_context == "custom-ctx"- assert p._bank_retain_mission == "Extract key facts"- assert p._recall_max_tokens == 2048- assert p._recall_types == ["world", "experience"]- assert p._recall_prompt_preamble == "Custom preamble:"- assert p._recall_max_input_chars == 500- assert p._bank_mission == "Test agent mission"-- def test_retain_source_defaults_empty(self, provider):- # Opt-in per AGENTS.md: no attribution tag ships by default.- assert provider._retain_source == ""-- def test_retain_source_absent_from_metadata_by_default(self, provider):- # metadata.source is stamped only when the user sets retain_source.- meta = provider._build_metadata(message_count=2, turn_index=1)- assert "source" not in meta-- def test_retain_source_user_override_wins(self, provider_with_config):- # Users can still opt in explicitly (config key / env var).- p = provider_with_config(retain_source="cogoport")- assert p._retain_source == "cogoport"- assert p._build_metadata(message_count=2, turn_index=1)["source"] == "cogoport"-- def test_embedded_profile_env_includes_idle_timeout_from_config(self):- env = _build_embedded_profile_env({- "llm_provider": "openai",- "llm_model": "gpt-4o-mini",- "idle_timeout": 0,- })-- assert env["HINDSIGHT_EMBED_DAEMON_IDLE_TIMEOUT"] == "0"--- def test_get_client_passes_idle_timeout_to_hindsight_embedded(self, monkeypatch):- captured = {}-- class FakeHindsightEmbedded:- def __init__(self, **kwargs):- captured.update(kwargs)-- monkeypatch.setitem(sys.modules, "hindsight", SimpleNamespace(HindsightEmbedded=FakeHindsightEmbedded))- monkeypatch.setattr("plugins.memory.hindsight._check_local_runtime", lambda: (True, ""))-- p = HindsightMemoryProvider()- p._mode = "local_embedded"- p._config = {- "profile": "hermes",- "llm_provider": "openai_compatible",- "llm_api_key": "test-key",- "llm_model": "test-model",- "idle_timeout": 0,- }- p._llm_base_url = "http://localhost:8060/v1"-- p._get_client()-- assert captured["idle_timeout"] == 0- assert captured["llm_provider"] == "openai"---class TestPostSetup:- def test_setup_cancel_at_mode_picker_writes_nothing(self, tmp_path, monkeypatch):- hermes_home = tmp_path / "hermes-home"- user_home = tmp_path / "user-home"- user_home.mkdir()- monkeypatch.setenv("HOME", str(user_home))- monkeypatch.setattr("plugins.memory.hindsight.get_hermes_home", lambda: hermes_home)-- save_config = MagicMock()- which = MagicMock(return_value="/usr/bin/uv")- run = MagicMock()- monkeypatch.setattr("hermes_cli.memory_setup._curses_select", lambda *args, **kwargs: _CANCELLED)- monkeypatch.setattr("shutil.which", which)- monkeypatch.setattr("subprocess.run", run)- monkeypatch.setattr("builtins.input", MagicMock(side_effect=AssertionError("prompt should not run")))- monkeypatch.setattr("getpass.getpass", MagicMock(side_effect=AssertionError("prompt should not run")))- monkeypatch.setattr("hermes_cli.config.save_config", save_config)-- provider = HindsightMemoryProvider()- provider.post_setup(str(hermes_home), {"memory": {"provider": "builtin"}})-- save_config.assert_not_called()- which.assert_not_called()- run.assert_not_called()- assert not (hermes_home / ".env").exists()- assert not (hermes_home / "hindsight" / "config.json").exists()- assert not (user_home / ".hindsight" / "profiles" / "hermes.env").exists()--- def test_local_embedded_setup_materializes_profile_env(self, tmp_path, monkeypatch):- hermes_home = tmp_path / "hermes-home"- user_home = tmp_path / "user-home"- user_home.mkdir()- monkeypatch.setenv("HOME", str(user_home))-- selections = iter([1, 0]) # local_embedded, openai- monkeypatch.setattr("hermes_cli.memory_setup._curses_select", lambda *args, **kwargs: next(selections))- monkeypatch.setattr("shutil.which", lambda name: None)- monkeypatch.setattr("builtins.input", lambda prompt="": "")- monkeypatch.setattr("sys.stdin.isatty", lambda: True)- monkeypatch.setattr("getpass.getpass", lambda prompt="": "sk-local-test")- saved_configs = []- monkeypatch.setattr("hermes_cli.config.save_config", lambda cfg: saved_configs.append(cfg.copy()))-- provider = HindsightMemoryProvider()- provider.post_setup(str(hermes_home), {"memory": {}})-- assert saved_configs[-1]["memory"]["provider"] == "hindsight"- env_text = (hermes_home / ".env").read_text()- assert "HINDSIGHT_LLM_API_KEY=sk-local-test\n" in env_text- assert "HINDSIGHT_TIMEOUT=120\n" in env_text- assert "HINDSIGHT_IDLE_TIMEOUT=300\n" in env_text-- profile_env = user_home / ".hindsight" / "profiles" / "hermes.env"- assert profile_env.exists()- assert profile_env.read_text() == (- "HINDSIGHT_API_LLM_PROVIDER=openai\n"- "HINDSIGHT_API_LLM_API_KEY=sk-local-test\n"- "HINDSIGHT_API_LLM_MODEL=gpt-4o-mini\n"- "HINDSIGHT_API_LOG_LEVEL=info\n"- "HINDSIGHT_EMBED_DAEMON_IDLE_TIMEOUT=300\n"- )---# ----------------------------------------------------------------------------# Tool handler tests-# ------------------------------------------------------------------------------class TestToolHandlers:- def test_retain_success(self, provider):- result = json.loads(provider.handle_tool_call(- "hindsight_retain", {"content": "user likes dark mode"}- ))- assert result["result"] == "Memory stored successfully."- provider._client.aretain_batch.assert_called_once()- call_kwargs = provider._client.aretain_batch.call_args.kwargs- assert call_kwargs["bank_id"] == "test-bank"- item = call_kwargs["items"][0]- assert item["content"] == "user likes dark mode"- # bank_id/retain_async are call-level args, never item keys.- assert "bank_id" not in item- assert "retain_async" not in item-- def test_retain_defaults_item_timestamp_when_no_occurred_at(self, provider, monkeypatch):- event_time = datetime(2026, 8, 24, 9, 30, tzinfo=ZoneInfo("America/Los_Angeles"))- monkeypatch.setattr("plugins.memory.hindsight._hermes_now", lambda: event_time)- result = json.loads(provider.handle_tool_call(- "hindsight_retain", {"content": "user likes dark mode"}- ))- assert result["result"] == "Memory stored successfully."- item = provider._client.aretain_batch.call_args.kwargs["items"][0]- # Non-temporal retains still carry a defaulted event timestamp so the- # server can resolve any relative time phrases (#93568).- assert item["timestamp"] == event_time.isoformat(timespec="seconds")-- def test_retain_threads_explicit_occurred_at_into_item_timestamp(self, provider):- result = json.loads(provider.handle_tool_call(- "hindsight_retain",- {"content": "user visited Paris", "occurred_at": "2026-03-03"},- ))- assert result["result"] == "Memory stored successfully."- item = provider._client.aretain_batch.call_args.kwargs["items"][0]- assert item["timestamp"] == "2026-03-03"-- def test_retain_ignores_blank_occurred_at(self, provider, monkeypatch):- event_time = datetime(2026, 8, 24, 9, 30, tzinfo=ZoneInfo("America/Los_Angeles"))- monkeypatch.setattr("plugins.memory.hindsight._hermes_now", lambda: event_time)- json.loads(provider.handle_tool_call(- "hindsight_retain", {"content": "hello", "occurred_at": " "}- ))- item = provider._client.aretain_batch.call_args.kwargs["items"][0]- assert item["timestamp"] == event_time.isoformat(timespec="seconds")-- def test_build_retain_kwargs_accepts_explicit_occurred_at(self, provider):- item = provider._build_retain_kwargs("dinner with Sam", occurred_at="2026-08-20T19:00:00+02:00")- assert item["timestamp"] == "2026-08-20T19:00:00+02:00"-- def test_retain_schema_exposes_occurred_at(self):- from plugins.memory.hindsight import RETAIN_SCHEMA-- props = RETAIN_SCHEMA["parameters"]["properties"]- assert "occurred_at" in props- assert props["occurred_at"]["type"] == "string"- # The description must steer the model to pass event times.- assert "event" in props["occurred_at"]["description"].lower()- assert "occurred_at" not in RETAIN_SCHEMA["parameters"]["required"]--- def test_recall_success(self, provider):- result = json.loads(provider.handle_tool_call(- "hindsight_recall", {"query": "dark mode"}- ))- assert "Memory 1" in result["result"]- assert "Memory 2" in result["result"]--- def test_reflect_success(self, provider):- result = json.loads(provider.handle_tool_call(- "hindsight_reflect", {"query": "summarize"}- ))- assert result["result"] == "Synthesized answer"--- def test_unknown_tool(self, provider):- result = json.loads(provider.handle_tool_call(- "hindsight_unknown", {}- ))- assert "error" in result--- def test_local_embedded_recall_reconnects_after_idle_shutdown(self, provider, monkeypatch):- first_client = _make_mock_client()- first_client.arecall.side_effect = RuntimeError("Cannot connect to host 127.0.0.1:8888")- second_client = _make_mock_client()- second_client.arecall.return_value = SimpleNamespace(- results=[SimpleNamespace(text="Recovered memory")]- )- clients = iter([first_client, second_client])-- provider._mode = "local_embedded"- provider._client = first_client- monkeypatch.setattr(provider, "_get_client", lambda: next(clients))-- result = json.loads(provider.handle_tool_call(- "hindsight_recall", {"query": "test"}- ))-- assert result["result"] == "1. Recovered memory"- assert provider._client is second_client- first_client.arecall.assert_called_once()- second_client.arecall.assert_called_once()---# ----------------------------------------------------------------------------# Prefetch tests-# ------------------------------------------------------------------------------class TestPrefetch:- def test_prefetch_returns_empty_when_no_result(self, provider):- assert provider.prefetch("test") == ""--- def test_recall_sync_defaults_off(self, provider):- assert provider._recall_sync is False-- def test_recall_sync_recalls_current_query_synchronously(self, provider_with_config):- # recall_sync=True: prefetch() must do a live recall against the- # *current* query (not read a previously queued buffer). #5820- p = provider_with_config(recall_sync=True)- captured = {}-- def _capture_recall(**kwargs):- captured["query"] = kwargs.get("query", "")- return SimpleNamespace(results=[SimpleNamespace(text="fresh memory")])-- p._client.arecall = AsyncMock(side_effect=_capture_recall)-- # Nothing pre-buffered — proves the result comes from a live recall.- assert p._prefetch_result == ""- result = p.prefetch("fix tests")-- assert captured["query"] == "fix tests" # current query, not ignored- assert "fresh memory" in result- p._client.arecall.assert_called_once()-- def test_recall_sync_skips_background_queue(self, provider_with_config):- # With sync recall there's nothing to prime in the background.- p = provider_with_config(recall_sync=True)- p.queue_prefetch("anything")- assert p._prefetch_thread is None-- def test_async_default_ignores_current_query_and_reads_buffer(self, provider):- # Default (recall_sync off): prefetch returns the buffered result and- # does NOT issue a live recall for the current query.- provider._prefetch_result = "- buffered from previous turn"- result = provider.prefetch("a totally different current query")- assert "buffered from previous turn" in result- provider._client.arecall.assert_not_called()-- def test_queue_prefetch_skipped_in_tools_mode(self, provider_with_config):- p = provider_with_config(memory_mode="tools")- p.queue_prefetch("test")- # Should not start a thread- assert p._prefetch_thread is None-- def test_prefetch_waits_for_pending_retain_before_recall(self, provider):- """The background prefetch must wait for queued retains to drain so the- next turn's recall observes the just-completed turn (no retain race)."""- import threading-- order = []- release = threading.Event()-- async def _slow_retain(*args, **kwargs):- release.wait(timeout=5.0)- order.append("retain")-- async def _recall(**kwargs):- order.append("recall")- return SimpleNamespace(results=[SimpleNamespace(text="m")])-- provider._client.aretain_batch = AsyncMock(side_effect=_slow_retain)- provider._client.arecall = AsyncMock(side_effect=_recall)-- # Enqueue a slow retain, then immediately queue the next-turn prefetch.- provider.sync_turn("hello", "world")- provider.queue_prefetch("next turn query")-- # Let the prefetch thread start and reach the drain barrier.- time.sleep(0.2)- assert order == [], "recall ran before the pending retain drained"-- # Release the retain; the prefetch should now proceed AFTER it.- release.set()- if provider._prefetch_thread:- provider._prefetch_thread.join(timeout=5.0)- provider._retain_queue.join()- assert order and order[0] == "retain"- assert "recall" in order-- def test_prefetch_wait_for_retain_can_be_disabled(self, provider_with_config):- p = provider_with_config(prefetch_waits_for_retain=False)- p._client = _make_mock_client()- assert p._prefetch_waits_for_retain is False---class TestPrefetchServerRetainVisibility:- """PR #62871 review follow-up: draining the local writer queue is not a- read-after-write signal for async retains. With ``retain_async=True`` the- server accepts the write and returns an ``operation_id`` that stays- ``pending`` until the write is durable/recall-visible. The background- prefetch must gate on server-side operation completion, not just the local- queue, before recalling.- """-- def _client_with_ops(self, statuses):- """Mock client whose aretain_batch returns an async operation_id and- whose operations.get_operation_status yields *statuses* in order- (last value repeats)."""- client = _make_mock_client()- client.aretain_batch = AsyncMock(- return_value=SimpleNamespace(operation_id="op-1", operation_ids=None)- )- seq = list(statuses)-- async def _status(**kwargs):- value = seq.pop(0) if len(seq) > 1 else seq[0]- return SimpleNamespace(status=value)-- client.operations = MagicMock()- client.operations.get_operation_status = AsyncMock(side_effect=_status)- return client-- def test_tracks_async_operation_id_from_retain(self, provider):- provider._client.aretain_batch = AsyncMock(- return_value=SimpleNamespace(operation_id="op-async-1", operation_ids=None)- )- provider.sync_turn("hello", "world")- provider._retain_queue.join()- assert "op-async-1" in provider._pending_retain_ops-- def test_tracks_multiple_operation_ids(self, provider):- provider._client.aretain_batch = AsyncMock(- return_value=SimpleNamespace(- operation_id=None, operation_ids=["op-a", "op-b"]- )- )- provider.sync_turn("hello", "world")- provider._retain_queue.join()- assert {"op-a", "op-b"} <= provider._pending_retain_ops-- def test_sync_retain_tracks_no_ops(self, provider_with_config):- p = provider_with_config(retain_async=False)- p._client = _make_mock_client()- p._client.aretain_batch = AsyncMock(- return_value=SimpleNamespace(operation_id="op-x", operation_ids=None)- )- p.sync_turn("hello", "world")- p._retain_queue.join()- # retain_async=False → no server-side op to wait on.- assert p._pending_retain_ops == set()-- def test_prefetch_waits_for_server_completion_before_recall(self, provider):- """Recall must not run until the tracked async op reports completed."""- order = []-- async def _recall(**kwargs):- order.append("recall")- return SimpleNamespace(results=[SimpleNamespace(text="m")])-- provider._client = self._client_with_ops(["pending", "pending", "completed"])- provider._client.arecall = AsyncMock(side_effect=_recall)-- provider.sync_turn("hello", "world")- provider._retain_queue.join()- assert "op-1" in provider._pending_retain_ops-- provider.queue_prefetch("next turn query")- if provider._prefetch_thread:- provider._prefetch_thread.join(timeout=5.0)-- # Recall ran, the op was polled to completion, and the pending set- # was cleared (so a later prefetch won't re-poll it).- assert order == ["recall"]- assert provider._client.operations.get_operation_status.await_count >= 3- assert provider._pending_retain_ops == set()-- def test_prefetch_proceeds_after_server_wait_timeout(self, provider_with_config):- """A wedged/never-completing async op must not hang prefetch forever;- it recalls anyway once the drain budget is exhausted."""- p = provider_with_config(prefetch_retain_drain_timeout=0.3)- order = []-- async def _recall(**kwargs):- order.append("recall")- return SimpleNamespace(results=[SimpleNamespace(text="m")])-- p._client = self._client_with_ops(["pending"]) # never completes- p._client.arecall = AsyncMock(side_effect=_recall)-- p.sync_turn("hello", "world")- p._retain_queue.join()-- start = time.monotonic()- p.queue_prefetch("next turn query")- if p._prefetch_thread:- p._prefetch_thread.join(timeout=5.0)- elapsed = time.monotonic() - start-- assert order == ["recall"], "prefetch should recall after the timeout"- assert elapsed < 3.0, "prefetch must not block well past the drain budget"-- def test_timed_out_ops_are_dropped_not_repolled(self, provider_with_config):- """Ops unresolved at deadline must be EVICTED so a permanently failing- status endpoint can't make every later prefetch re-burn the full- timeout on a growing pending set (unbounded session-wide degradation- + reply-path join penalty)."""- p = provider_with_config(prefetch_retain_drain_timeout=0.3)- p._client = self._client_with_ops(["pending"]) # never completes- p._client.arecall = AsyncMock(- return_value=SimpleNamespace(results=[SimpleNamespace(text="m")])- )-- p.sync_turn("hello", "world")- p._retain_queue.join()- assert p._pending_retain_ops, "op should be tracked before the wait"-- # First prefetch burns the budget and must DROP the wedged op.- p.queue_prefetch("q1")- if p._prefetch_thread:- p._prefetch_thread.join(timeout=5.0)- assert p._pending_retain_ops == set(), (- "unresolved ops must be evicted at deadline, not retained"- )-- # A later prefetch with nothing pending must be near-instant.- start = time.monotonic()- p.queue_prefetch("q2")- if p._prefetch_thread:- p._prefetch_thread.join(timeout=5.0)- assert time.monotonic() - start < 0.25, (- "second prefetch re-polled dropped ops — eviction regressed"- )-- def test_operation_notfound_treated_as_complete(self, provider):- """A NotFound (completed+evicted) op is treated as done, not pending."""- exceptions = pytest.importorskip(- "hindsight_client_api.exceptions",- reason="Hindsight SDK is not installed",- )- NotFoundException = exceptions.NotFoundException-- client = _make_mock_client()- client.operations = MagicMock()- client.operations.get_operation_status = AsyncMock(- side_effect=NotFoundException(status=404, reason="gone")- )- provider._client = client-- assert provider._is_retain_op_complete("bank", "op-gone") is True-- def test_transient_status_error_keeps_waiting(self, provider):- """A transient status-check error means 'unknown', so keep waiting."""- client = _make_mock_client()- client.operations = MagicMock()- client.operations.get_operation_status = AsyncMock(- side_effect=RuntimeError("temporary blip")- )- provider._client = client-- assert provider._is_retain_op_complete("bank", "op-1") is False---# ----------------------------------------------------------------------------# recall_status (deterministic recall indicator) tests-# ------------------------------------------------------------------------------class TestRecallStatus:- def test_none_before_any_prefetch(self, provider):- # Nothing recalled yet → no indicator.- assert provider.recall_status() is None-- def test_reports_count_after_recall(self, provider):- # Mock client returns 2 memories; prefetch consumes the block.- provider.queue_prefetch("test")- if provider._prefetch_thread:- provider._prefetch_thread.join(timeout=5.0)- provider.prefetch("test")-- status = provider.recall_status()- assert status is not None- assert status.provider_label == "Hindsight"- assert status.count == 2-- def test_reports_count_in_recall_sync_mode(self, provider_with_config):- # recall_sync path does a live recall inside prefetch() (no background- # prime) — the indicator must still report the count for that turn.- p = provider_with_config(recall_sync=True)- assert p.prefetch("test") # live recall returns the 2 mock memories- status = p.recall_status()- assert status is not None- assert status.count == 2-- def test_none_when_recall_returned_nothing(self, provider):- provider._client.arecall = AsyncMock(- return_value=SimpleNamespace(results=[])- )- provider.queue_prefetch("test")- if provider._prefetch_thread:- provider._prefetch_thread.join(timeout=5.0)- assert provider.prefetch("test") == ""- assert provider.recall_status() is None-- def test_stale_count_cleared_on_empty_turn(self, provider):- # First turn recalls 2 memories.- provider.queue_prefetch("test")- if provider._prefetch_thread:- provider._prefetch_thread.join(timeout=5.0)- provider.prefetch("test")- assert provider.recall_status().count == 2-- # Next turn recalls nothing — the prior count must not linger.- provider._client.arecall = AsyncMock(- return_value=SimpleNamespace(results=[])- )- provider.queue_prefetch("test2")- if provider._prefetch_thread:- provider._prefetch_thread.join(timeout=5.0)- provider.prefetch("test2")- assert provider.recall_status() is None-- def test_suppressed_when_indicator_off(self, provider_with_config):- p = provider_with_config(recall_indicator=False)- p.queue_prefetch("test")- if p._prefetch_thread:- p._prefetch_thread.join(timeout=5.0)- p.prefetch("test")- # Memory was injected, but the indicator is turned off.- assert p._last_recall_returned is True- assert p.recall_status() is None-- def test_reflect_mode_reports_generic_count(self, provider_with_config):- p = provider_with_config(recall_prefetch_method="reflect")- p.queue_prefetch("test")- if p._prefetch_thread:- p._prefetch_thread.join(timeout=5.0)- p.prefetch("test")- status = p.recall_status()- assert status is not None- # Reflect synthesizes across memories → no discrete count (0).- assert status.count == 0---# ----------------------------------------------------------------------------# sync_turn tests-# ------------------------------------------------------------------------------class TestSyncTurn:- def test_sync_turn_retains_metadata_rich_turn(self, provider_with_config, monkeypatch):- event_time = datetime(2026, 8, 10, 11, 9, tzinfo=ZoneInfo("Asia/Shanghai"))- monkeypatch.setattr("plugins.memory.hindsight._hermes_now", lambda: event_time)- p = provider_with_config(- retain_tags=["conv", "session1"],- retain_source="hermes",- retain_user_prefix="User (fakeusername)",- retain_assistant_prefix="Assistant (fakeassistantname)",- )- p.initialize(- session_id="session-1",- platform="discord",- user_id="fakeusername-123",- user_name="fakeusername",- chat_id="1485316232612941897",- chat_name="fakeassistantname-forums",- chat_type="thread",- thread_id="1491249007475949698",- agent_identity="fakeassistantname",- )- p._client = _make_mock_client()-- p.sync_turn("hello", "hi there")- p._retain_queue.join()-- p._client.aretain_batch.assert_called_once()- call_kwargs = p._client.aretain_batch.call_args.kwargs- assert call_kwargs["bank_id"] == "test-bank"- assert call_kwargs["document_id"].startswith("session-1-")- assert call_kwargs["retain_async"] is True- assert len(call_kwargs["items"]) == 1- item = call_kwargs["items"][0]- assert item["context"] == "conversation between Hermes Agent and the User"- assert item["tags"] == ["conv", "session1", "session:session-1"]- content = json.loads(item["content"])- assert len(content) == 1- assert content[0][0]["role"] == "user"- assert content[0][0]["content"] == "User (fakeusername): hello"- assert content[0][1]["role"] == "assistant"- assert content[0][1]["content"] == "Assistant (fakeassistantname): hi there"- assert item["metadata"]["source"] == "hermes"- assert item["metadata"]["session_id"] == "session-1"- assert item["metadata"]["platform"] == "discord"- assert item["metadata"]["user_id"] == "fakeusername-123"- assert item["metadata"]["user_name"] == "fakeusername"- assert item["metadata"]["chat_id"] == "1485316232612941897"- assert item["metadata"]["chat_name"] == "fakeassistantname-forums"- assert item["metadata"]["chat_type"] == "thread"- assert item["metadata"]["thread_id"] == "1491249007475949698"- assert item["metadata"]["agent_identity"] == "fakeassistantname"- assert item["metadata"]["turn_index"] == "1"- assert item["metadata"]["message_count"] == "2"- assert content[0][0]["timestamp"] == event_time.isoformat(timespec="seconds")- assert content[0][1]["timestamp"] == event_time.isoformat(timespec="seconds")- assert re.fullmatch(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z", item["metadata"]["retained_at"])- assert item["timestamp"] == event_time.isoformat(timespec="seconds")-- def test_retain_timestamp_normalizes_a_naive_clock(self, provider, monkeypatch):- event_time = datetime(2026, 8, 10, 11, 9)- monkeypatch.setattr("plugins.memory.hindsight._hermes_now", lambda: event_time)-- timestamp = provider._build_retain_kwargs("hello")["timestamp"]- parsed = datetime.fromisoformat(timestamp)-- assert parsed.tzinfo is not None- assert parsed.utcoffset() is not None-- @pytest.mark.asyncio- async def test_retain_timestamp_is_serialized_by_pinned_client(self, provider):- hindsight_client = pytest.importorskip(- "hindsight_client", reason="pinned hindsight-client SDK not installed"- )- Hindsight = hindsight_client.Hindsight-- item = provider._build_retain_kwargs("hello")- item.pop("bank_id", None)- item.pop("retain_async", None)-- client = Hindsight(base_url="http://localhost:9999", api_key="test-key")- client._memory_api.retain_memories = AsyncMock(return_value=SimpleNamespace(ok=True))- try:- await client.aretain_batch(bank_id="test-bank", items=[item])- call = client._memory_api.retain_memories.await_args- assert call is not None- request = call.args[1]- assert request.to_dict()["items"][0]["timestamp"] == item["timestamp"]- finally:- await client.aclose()--- def test_resume_creates_new_document(self, tmp_path, monkeypatch):- """Resuming a session (re-initializing) gets a new document_id- so previously stored content is not overwritten."""- config = {"mode": "cloud", "apiKey": "k", "api_url": "http://x", "bank_id": "b"}- config_path = tmp_path / "hindsight" / "config.json"- config_path.parent.mkdir(parents=True, exist_ok=True)- config_path.write_text(json.dumps(config))- monkeypatch.setattr("plugins.memory.hindsight.get_hermes_home", lambda: tmp_path)-- p1 = HindsightMemoryProvider()- p1.initialize(session_id="resumed-session", hermes_home=str(tmp_path), platform="cli")-- # Sleep just enough that the microsecond timestamp differs- import time- time.sleep(0.001)-- p2 = HindsightMemoryProvider()- p2.initialize(session_id="resumed-session", hermes_home=str(tmp_path), platform="cli")-- # Same session, but each process gets its own document_id- assert p1._document_id != p2._document_id- assert p1._document_id.startswith("resumed-session-")- assert p2._document_id.startswith("resumed-session-")---# ----------------------------------------------------------------------------# retain indicator ("saving to memory") tests-# ------------------------------------------------------------------------------class TestRetainIndicator:- _SAVING = "👁️ Hindsight — saving to memory…"-- def test_emits_saving_on_dispatch(self, provider_with_config):- calls = []- p = provider_with_config(retain_async=False)- p._status_callback = calls.append- p.sync_turn("hello", "hi")- p._retain_queue.join()- assert self._SAVING in calls-- def test_suppressed_when_indicator_off(self, provider_with_config):- calls = []- p = provider_with_config(retain_indicator=False, retain_async=False)- p._status_callback = calls.append- p.sync_turn("hello", "hi")- p._retain_queue.join()- assert calls == []-- def test_no_emit_when_auto_retain_off(self, provider_with_config):- calls = []- p = provider_with_config(auto_retain=False)- p._status_callback = calls.append- p.sync_turn("hello", "hi") # returns early — nothing dispatched- assert calls == []-- def test_no_emit_on_buffered_turn(self, provider_with_config):- # retain_every_n_turns=2: turn 1 buffers (no write, no line),- # turn 2 flushes (one line) — "saving" only fires on a real write.- calls = []- p = provider_with_config(retain_every_n_turns=2, retain_async=False)- p._status_callback = calls.append- p.sync_turn("t1-u", "t1-a")- assert calls == []- p.sync_turn("t2-u", "t2-a")- p._retain_queue.join()- assert calls == [self._SAVING]-- def test_no_crash_without_callback(self, provider_with_config):- p = provider_with_config(retain_async=False)- assert p._status_callback is None- p.sync_turn("hello", "hi") # must not raise- p._retain_queue.join()-- def test_status_callback_wired_from_initialize(self, tmp_path, monkeypatch):- cb = lambda _m: None- p = _provider_for_mode(tmp_path, monkeypatch, "cloud")- p.initialize(session_id="s", hermes_home=str(tmp_path), status_callback=cb)- assert p._status_callback is cb---# ----------------------------------------------------------------------------# Shutdown / writer tests-# ------------------------------------------------------------------------------class TestShutdownRace:- def test_sync_turn_uses_single_writer_thread(self, provider):- """All retains run through one long-lived writer thread."""- provider.sync_turn("a", "b")- provider._retain_queue.join()- first_writer = provider._writer_thread- assert first_writer is not None- assert first_writer.is_alive()-- provider.sync_turn("c", "d")- provider._retain_queue.join()- # Same thread reused — no ad-hoc thread per call.- assert provider._writer_thread is first_writer- assert provider._client.aretain_batch.call_count == 2--- def test_shutdown_drains_pending_retains(self, provider):- """Shutdown must wait for queued retains to complete, not abandon them.-- Otherwise the LAST in-flight turn — typically the most important —- is silently lost.- """- client = provider._client- provider.sync_turn("a", "b")- provider.sync_turn("c", "d")- provider.shutdown()- # Both retains drained before shutdown returned.- assert client.aretain_batch.call_count == 2- assert provider._retain_queue.empty()---# ----------------------------------------------------------------------------# on_session_switch — flush + prefetch reset behavior-# ------------------------------------------------------------------------------class TestSessionSwitchBufferFlush:- def test_buffered_turns_flushed_before_clear(self, provider_with_config):- """retain_every_n_turns > 1 must not silently drop partial buffers- on session switch. Whatever's in _session_turns at switch time- should land in the OLD document under the OLD session id."""- p = provider_with_config(retain_every_n_turns=3, retain_async=False)- old_doc = p._document_id-- # Two turns buffered, no retain yet (boundary is at turn 3). The- # writer hasn't been started either — sync_turn's early return- # skips _ensure_writer when no retain is due.- p.sync_turn("turn1-user", "turn1-asst")- p.sync_turn("turn2-user", "turn2-asst")- assert p._sync_thread is None- p._client.aretain_batch.assert_not_called()-- # Switch — flush should fire under OLD document_id via the writer queue.- p.on_session_switch("new-sid", parent_session_id="test-session", reset=True)- p._retain_queue.join()-- p._client.aretain_batch.assert_called_once()- kw = p._client.aretain_batch.call_args.kwargs- assert kw["document_id"] == old_doc- item = kw["items"][0]- # Both buffered turns must be present in the flushed payload.- content = json.loads(item["content"])- flat = json.dumps(content)- assert "turn1-user" in flat- assert "turn2-user" in flat- # Old session id must appear in lineage tags / metadata.- assert "session:test-session" in item["tags"]- assert item["metadata"]["session_id"] == "test-session"-- # And the new session must start with a clean slate.- assert p._session_id == "new-sid"- assert p._session_turns == []- assert p._turn_counter == 0- assert p._document_id != old_doc- assert p._document_id.startswith("new-sid-")--- def test_in_flight_prefetch_thread_drained_on_switch(self, provider, monkeypatch):- """on_session_switch must wait for an in-flight prefetch from the- old session to settle before clearing _prefetch_result, otherwise- the thread can race and re-populate the field after the clear."""- import threading-- gate = threading.Event()- finished = threading.Event()-- def _slow_prefetch():- gate.wait(timeout=5.0)- with provider._prefetch_lock:- provider._prefetch_result = "old-session recall"- finished.set()-- provider._prefetch_thread = threading.Thread(target=_slow_prefetch, daemon=True)- provider._prefetch_thread.start()-- # Release the prefetch worker so it writes _prefetch_result, then- # call on_session_switch — it must join the thread before clearing.- gate.set()- provider.on_session_switch("new-sid")-- assert finished.is_set(), "switch returned before prefetch thread settled"- assert provider._prefetch_result == ""-- def test_flush_serializes_behind_pending_retains_via_writer_queue(- self, provider_with_config- ):- """The flush closure must ride the same _retain_queue sync_turn- uses, so it lands FIFO behind any still-queued old-session- retains rather than racing them on a separate thread.-- Regression guard: an earlier draft spawned a raw threading.Thread- for flush, overwriting _sync_thread and racing the writer against- the same document_id.- """- import threading as _threading-- p = provider_with_config(retain_every_n_turns=2, retain_async=False)-- # Block the first writer job until we've enqueued the flush- # behind it. This proves ordering — the flush MUST wait.- gate = _threading.Event()- call_order: list[str] = []-- def _aretain_batch_tracking(**kw):- idx = kw["items"][0]["metadata"].get("turn_index", "")- call_order.append(str(idx))- if idx == "2":- # First retain blocks until we've enqueued the flush.- gate.wait(timeout=5.0)-- p._client.aretain_batch = AsyncMock(side_effect=_aretain_batch_tracking)-- # Turn 1+2 → boundary hit → retain enqueued (will block).- p.sync_turn("turn1-user", "turn1-asst")- p.sync_turn("turn2-user", "turn2-asst")-- # One more buffered turn so flush has something to land.- p.sync_turn("turn3-user", "turn3-asst")-- # Switch while the first retain is still blocked on `gate`.- p.on_session_switch("new-sid", parent_session_id="test-session")-- # Release the first retain. Flush must have been enqueued- # BEHIND it, and run second.- gate.set()- p._retain_queue.join()-- # The flush carries all buffered turns; sync_turn's retain #2- # carried the batch at boundary time. Two distinct calls.- assert p._client.aretain_batch.call_count == 2- # First call landed while buffer was [t1, t2]; flush landed- # after we added t3. So the second call must be strictly after.- assert call_order[0] == "2"- # Flush retain has turn_index matching the buffered count at- # switch time (3 turns accumulated, _turn_index was set to 3- # by the last sync_turn).- assert call_order[1] == "3"---# ----------------------------------------------------------------------------# update_mode='append' capability probe + retain dispatch-# ------------------------------------------------------------------------------class TestUpdateModeAppendCapability:- def _clear_capability_cache(self):- from plugins.memory.hindsight import _append_capability_cache, _append_capability_lock- with _append_capability_lock:- _append_capability_cache.clear()-- def test_legacy_api_falls_back_to_per_process_doc_id(self, provider, monkeypatch):- """API returns no /version (or pre-0.5.0) — sync_turn must use the- per-process unique doc_id and NOT pass update_mode."""- self._clear_capability_cache()- monkeypatch.setattr(- "plugins.memory.hindsight._fetch_hindsight_api_version",- lambda *a, **kw: None,- )- old_doc = provider._document_id- provider.sync_turn("hello", "hi")- provider._retain_queue.join()-- kw = provider._client.aretain_batch.call_args.kwargs- assert kw["document_id"] == old_doc- assert kw["document_id"].startswith("test-session-")- item = kw["items"][0]- assert "update_mode" not in item-- def test_modern_api_uses_stable_doc_id_with_append(self, provider, monkeypatch):- """API on >=0.5.0 — retain uses stable session_id and sets update_mode='append'."""- self._clear_capability_cache()- monkeypatch.setattr(- "plugins.memory.hindsight._fetch_hindsight_api_version",- lambda *a, **kw: "0.5.6",- )- provider.sync_turn("hello", "hi")- provider._retain_queue.join()-- kw = provider._client.aretain_batch.call_args.kwargs- # Stable: just the session id, no per-process timestamp suffix.- assert kw["document_id"] == "test-session"- item = kw["items"][0]- assert item["update_mode"] == "append"--- def test_session_switch_flush_picks_capability_against_old_session(- self, provider_with_config, monkeypatch- ):- """When the API supports append, the flush on /reset must land- in the OLD session's stable document, not a per-process id."""- self._clear_capability_cache()- monkeypatch.setattr(- "plugins.memory.hindsight._fetch_hindsight_api_version",- lambda *a, **kw: "0.5.6",- )- p = provider_with_config(retain_every_n_turns=3, retain_async=False)- p.sync_turn("turn1-user", "turn1-asst")- p.sync_turn("turn2-user", "turn2-asst")- p.on_session_switch("new-sid", parent_session_id="test-session", reset=True)- p._retain_queue.join()-- kw = p._client.aretain_batch.call_args.kwargs- # Flush goes to the OLD session's stable doc, not new-sid's.- assert kw["document_id"] == "test-session"- assert kw["items"][0]["update_mode"] == "append"---# ----------------------------------------------------------------------------# System prompt tests-# ------------------------------------------------------------------------------class TestSystemPrompt:- def test_hybrid_mode_prompt(self, provider):- block = provider.system_prompt_block()- assert "Hindsight Memory" in block- assert "hindsight_recall" in block- assert "automatically injected" in block---# ----------------------------------------------------------------------------# Config schema tests-# ------------------------------------------------------------------------------class TestConfigSchema:- def test_schema_has_all_new_fields(self, provider):- schema = provider.get_config_schema()- keys = {f["key"] for f in schema}- expected_keys = {- "mode", "api_url", "api_key", "llm_provider", "llm_api_key",- "llm_model", "bank_id", "bank_id_template", "bank_mission", "bank_retain_mission",- "recall_budget", "memory_mode", "recall_prefetch_method",- "retain_tags", "retain_source",- "retain_user_prefix", "retain_assistant_prefix",- "recall_tags", "recall_tags_match",- "auto_recall", "auto_retain",- "retain_every_n_turns", "retain_async", "retain_context",- "recall_max_tokens", "recall_max_input_chars",- "recall_prompt_preamble",- }- assert expected_keys.issubset(keys), f"Missing: {expected_keys - keys}"---# ----------------------------------------------------------------------------# bank_id_template tests-# ------------------------------------------------------------------------------class TestBankIdTemplate:- def test_sanitize_bank_segment_passthrough(self):- assert _sanitize_bank_segment("hermes") == "hermes"- assert _sanitize_bank_segment("my-agent_1") == "my-agent_1"--- def test_resolve_empty_template_uses_fallback(self):- result = _resolve_bank_id_template(- "", fallback="hermes", profile="coder"- )- assert result == "hermes"--- def test_resolve_sanitizes_placeholder_values(self):- result = _resolve_bank_id_template(- "user-{user}", fallback="hermes",- profile="", workspace="", platform="",- user="[email protected]", session="",- )- assert result == "user-josh-example-com"--- def test_provider_uses_bank_id_template_from_config(self, tmp_path, monkeypatch):- config = {- "mode": "cloud",- "apiKey": "k",- "api_url": "http://x",- "bank_id": "fallback-bank",- "bank_id_template": "hermes-{profile}",- }- config_path = tmp_path / "hindsight" / "config.json"- config_path.parent.mkdir(parents=True, exist_ok=True)- config_path.write_text(json.dumps(config))- monkeypatch.setattr("plugins.memory.hindsight.get_hermes_home", lambda: tmp_path)-- p = HindsightMemoryProvider()- p.initialize(- session_id="s1",- hermes_home=str(tmp_path),- platform="cli",- agent_identity="coder",- agent_workspace="hermes",- )- assert p._bank_id == "hermes-coder"- assert p._bank_id_template == "hermes-{profile}"---# ----------------------------------------------------------------------------# Availability tests-# ------------------------------------------------------------------------------class TestAvailability:- def test_available_with_api_key(self, tmp_path, monkeypatch):- monkeypatch.setattr(- "plugins.memory.hindsight.get_hermes_home",- lambda: tmp_path / "nonexistent",- )- monkeypatch.setenv("HINDSIGHT_API_KEY", "test-key")- p = HindsightMemoryProvider()- assert p.is_available()--- def test_local_mode_unavailable_when_runtime_import_fails(self, tmp_path, monkeypatch):- monkeypatch.setattr(- "plugins.memory.hindsight.get_hermes_home",- lambda: tmp_path / "nonexistent",- )- monkeypatch.setenv("HINDSIGHT_MODE", "local")-- def _raise(_name):- raise RuntimeError(- "NumPy was built with baseline optimizations: (x86_64-v2)"- )-- monkeypatch.setattr(- "importlib.import_module",- _raise,- )- p = HindsightMemoryProvider()- assert not p.is_available()-- def test_initialize_disables_local_mode_when_runtime_import_fails(self, tmp_path, monkeypatch):- config = {"mode": "local_embedded"}- config_path = tmp_path / "hindsight" / "config.json"- config_path.parent.mkdir(parents=True, exist_ok=True)- config_path.write_text(json.dumps(config))- monkeypatch.setattr(- "plugins.memory.hindsight.get_hermes_home", lambda: tmp_path- )-- def _raise(_name):- raise RuntimeError("x86_64-v2 unsupported")-- monkeypatch.setattr(- "importlib.import_module",- _raise,- )-- p = HindsightMemoryProvider()- p.initialize(session_id="test-session", hermes_home=str(tmp_path), platform="cli")- assert p._mode == "disabled"---class TestSharedEventLoopLifecycle:- """Regression tests for #11923 — Hindsight leaking aiohttp ClientSession /- TCPConnector objects in long-running gateway processes.-- Root cause: the module-global ``_loop`` / ``_loop_thread`` pair is shared- across every HindsightMemoryProvider instance in the process (the plugin- loader builds one provider per AIAgent, and the gateway builds one AIAgent- per concurrent chat session). When a session ended, ``shutdown()`` stopped- the shared loop, which orphaned every *other* live provider's aiohttp- ClientSession on a dead loop. Those sessions were never closed and surfaced- as ``Unclosed client session`` / ``Unclosed connector`` errors.- """-- def test_shutdown_does_not_stop_shared_event_loop(self, provider_with_config):- from plugins.memory import hindsight as hindsight_mod-- async def _noop():- return 1-- # Prime the shared loop by scheduling a trivial coroutine — mirrors- # the first time any real async call (arecall/aretain/areflect) runs.- assert hindsight_mod._run_sync(_noop()) == 1-- loop_before = hindsight_mod._loop- thread_before = hindsight_mod._loop_thread- assert loop_before is not None and loop_before.is_running()- assert thread_before is not None and thread_before.is_alive()-- # Build two independent providers (two concurrent chat sessions).- provider_a = provider_with_config()- provider_b = provider_with_config()-- # End session A.- provider_a.shutdown()-- # Module-global loop/thread must still be the same live objects —- # provider B (and any other sibling provider) is still relying on them.- assert hindsight_mod._loop is loop_before, (- "shutdown() swapped out the shared event loop — sibling providers "- "would have their aiohttp ClientSession orphaned (#11923)"- )- assert hindsight_mod._loop.is_running(), (- "shutdown() stopped the shared event loop — sibling providers' "- "aiohttp sessions would leak (#11923)"- )- assert hindsight_mod._loop_thread is thread_before- assert hindsight_mod._loop_thread.is_alive()-- # Provider B can still dispatch async work on the shared loop.- async def _still_working():- return 42-- assert hindsight_mod._run_sync(_still_working()) == 42-- provider_b.shutdown()-- def test_client_aclose_called_on_cloud_mode_shutdown(self, provider):- """Per-provider session cleanup still runs even though the shared- loop is preserved. Each provider's own aiohttp session is closed- via ``self._client.aclose()``; only the (empty) shared loop survives.- """- assert provider._client is not None- mock_client = provider._client-- provider.shutdown()-- mock_client.aclose.assert_called_once()- assert provider._client is None---class TestShutdown:- def test_local_embedded_shutdown_closes_inner_async_client_on_shared_loop(self, provider):- inner_client = _make_mock_client()- embedded = MagicMock()- embedded._client = inner_client- embedded.close = MagicMock()-- provider._mode = "local_embedded"- provider._client = embedded-- provider.shutdown()-- inner_client.aclose.assert_awaited_once()- embedded.close.assert_called_once()- assert embedded._client is None- assert provider._client is None--[email protected](os.name == "nt", reason="POSIX mode bits not enforced on Windows")-def test_save_config_sets_owner_only_permissions(tmp_path):- """hindsight/config.json must be written with 0o600 so API key is not world-readable."""- provider = HindsightMemoryProvider()- provider.save_config({"api_key": "hd-test-key"}, str(tmp_path))- config_file = tmp_path / "hindsight" / "config.json"- assert config_file.exists()- mode = stat.S_IMODE(config_file.stat().st_mode)- assert mode == 0o600, f"Expected 0o600 (owner-only), got {oct(mode)}"---def test_load_config_corrupt_profile_file_falls_through_to_env(tmp_path, monkeypatch):- """A corrupt $HERMES_HOME/hindsight/config.json is not the config: the loader falls through- (legacy file, then env) instead of returning an empty, silently-unconfigured mapping."""- home = tmp_path / "home"- (home / "hindsight").mkdir(parents=True)- (home / "hindsight" / "config.json").write_text("{not json", encoding="utf-8")- monkeypatch.setenv("HERMES_HOME", str(home))- monkeypatch.setattr(Path, "home", lambda: tmp_path / "nohome")- monkeypatch.setenv("HINDSIGHT_MODE", "local")- monkeypatch.setenv("HINDSIGHT_BANK_ID", "from-env")-- cfg = _load_config()-- assert cfg["mode"] == "local"- assert cfg["banks"]["hermes"]["bankId"] == "from-env"---class TestLoadSimpleEnv:- def test_bom_first_key_is_recognized(self, tmp_path):- """A Notepad-edited .env carries a BOM; the first key must still parse- instead of becoming '\ufeffHINDSIGHT_LLM_API_KEY'."""- env_path = tmp_path / ".env"- env_path.write_bytes("HINDSIGHT_LLM_API_KEY=sk-test\n".encode("utf-8"))- values = _load_simple_env(env_path)- assert values.get("HINDSIGHT_LLM_API_KEY") == "sk-test"---class TestPostSetupEnvEncoding:- def _run_cloud_post_setup(self, tmp_path, monkeypatch):- """Drive post_setup through the cloud path with piped stdin."""- import io-- monkeypatch.setattr("hermes_cli.memory_setup._curses_select",- lambda *a, **kw: 0) # cloud mode- monkeypatch.setattr("hermes_cli.config.save_config", lambda c: None)- # Skip the dependency install (now routed through lazy_deps, NS-605).- import tools.lazy_deps as lazy_deps_mod- monkeypatch.setattr(- lazy_deps_mod, "install_specs",- lambda *a, **kw: lazy_deps_mod.InstallSpecsResult(ok=True),- )- # First line: API key prompt (readline). Second line: API URL (input).- monkeypatch.setattr(sys, "stdin", io.StringIO("sk-new\n\n"))-- provider = HindsightMemoryProvider()- provider.post_setup(str(tmp_path), {"memory": {}})-- def test_bom_first_key_updated_in_place(self, tmp_path, monkeypatch):- """The setup writer reads the existing .env BOM-tolerantly, so a- BOM'd first key is matched and rewritten, not duplicated."""- env_path = tmp_path / ".env"- env_path.write_bytes("HINDSIGHT_API_KEY=old\n".encode("utf-8"))-- self._run_cloud_post_setup(tmp_path, monkeypatch)-- content = env_path.read_text(encoding="utf-8")- assert content.count("HINDSIGHT_API_KEY=") == 1- assert "HINDSIGHT_API_KEY=sk-new" in content- assert "old" not in content- assert "" not in content---class TestClientAutoUpgradeRoutesThroughLazyDeps:- """The initialize()-time hindsight-client auto-upgrade must go through- lazy_deps.install_specs() (environment-aware, durable-target on sealed- hosted venvs) — never a direct `uv pip install --python sys.executable`- subprocess, which fails with EROFS/EACCES on immutable images (NS-605)."""-- def _init_with_outdated_client(self, tmp_path, monkeypatch, outcome):- import importlib.metadata as md- import subprocess as subprocess_mod- import tools.lazy_deps as lazy_deps_mod-- config_path = tmp_path / "hindsight" / "config.json"- config_path.parent.mkdir(parents=True, exist_ok=True)- config_path.write_text(json.dumps({"mode": "cloud"}))- monkeypatch.setattr(- "plugins.memory.hindsight.get_hermes_home", lambda: tmp_path- )-- # Simulate an installed-but-outdated client.- monkeypatch.setattr(md, "version", lambda name: "0.0.1")-- calls = []- monkeypatch.setattr(- lazy_deps_mod, "install_specs",- lambda specs, **kw: calls.append(tuple(specs)) or outcome,- )-- # Regression guard: no direct pip subprocess may run.- def _no_subprocess(*a, **kw): # pragma: no cover - fails loudly- raise AssertionError(f"unexpected subprocess.run during auto-upgrade: {a}")- monkeypatch.setattr(subprocess_mod, "run", _no_subprocess)-- provider = HindsightMemoryProvider()- provider.initialize(session_id="s", hermes_home=str(tmp_path), platform="cli")- return calls-- def test_upgrade_uses_install_specs_not_subprocess(self, tmp_path, monkeypatch):- from plugins.memory.hindsight import _MIN_CLIENT_VERSION- from tools.lazy_deps import InstallSpecsResult-- calls = self._init_with_outdated_client(- tmp_path, monkeypatch, InstallSpecsResult(ok=True)- )- assert calls == [(f"hindsight-client>={_MIN_CLIENT_VERSION}",)]-- def test_blocked_upgrade_is_nonfatal_and_surfaces_reason(- self, tmp_path, monkeypatch, caplog- ):- import logging- from tools.lazy_deps import InstallSpecsResult-- with caplog.at_level(logging.WARNING):- calls = self._init_with_outdated_client(- tmp_path, monkeypatch,- InstallSpecsResult(ok=False, blocked=True,- reason="runtime installs are disabled on this deployment"),- )- assert len(calls) == 1 # attempted exactly once, init still completed- assert any("runtime installs are disabled" in r.getMessage()- for r in caplog.records)----class TestMultiplexBackgroundScope:- """Under multiplex_profiles get_secret fails closed on an unscoped thread;- the writer / daemon-start threads are spawned from a scoped context and- must carry it along (#92608, #94933)."""-- @pytest.fixture()- def scoped_embedded(self, tmp_path, monkeypatch):- from agent.secret_scope import (- build_profile_secret_scope, reset_secret_scope, set_multiplex_active, set_secret_scope,- )- from hermes_constants import reset_hermes_home_override, set_hermes_home_override-- created = []-- class FakeHindsightEmbedded:- def __init__(self, **kwargs):- created.append(kwargs["llm_api_key"])- self._manager = SimpleNamespace(is_running=lambda profile: False, stop=lambda profile: None)- self._ensure_started = lambda: None-- dem = SimpleNamespace(console=None)- monkeypatch.setitem(sys.modules, "hindsight", SimpleNamespace(HindsightEmbedded=FakeHindsightEmbedded))- monkeypatch.setitem(sys.modules, "hindsight_embed", SimpleNamespace(daemon_embed_manager=dem))- monkeypatch.setitem(sys.modules, "hindsight_embed.daemon_embed_manager", dem)- monkeypatch.setattr("plugins.memory.hindsight._check_local_runtime", lambda: (True, ""))-- home = tmp_path / "profiles" / "p1"- (home / "hindsight").mkdir(parents=True)- (home / ".env").write_text("HINDSIGHT_LLM_API_KEY=p1-secret\n")- (home / "hindsight" / "config.json").write_text(json.dumps(- {"mode": "local_embedded", "llm_provider": "openai", "llm_model": "m", "memory_mode": "hybrid"}- ))- # Enter the profile scope the way gateway _profile_runtime_scope does.- set_multiplex_active(True)- monkeypatch.setattr("plugins.memory.hindsight.get_hermes_home", lambda: home)- home_tok = set_hermes_home_override(str(home))- scope_tok = set_secret_scope(build_profile_secret_scope(home))- yield created, home- set_multiplex_active(False)- reset_secret_scope(scope_tok)- reset_hermes_home_override(home_tok)-- def test_writer_thread_resolves_profile_secret(self, scoped_embedded):- created, home = scoped_embedded- p = HindsightMemoryProvider()- p._mode = "local_embedded"- p._config = {"profile": "hermes", "llm_provider": "openai", "llm_model": "m"}- p._ensure_writer()- p._retain_queue.put(p._get_client) # real body: get_secret(HINDSIGHT_LLM_API_KEY)- p._retain_queue.put(_WRITER_SENTINEL)- p._writer_thread.join(timeout=5)- assert created == ["p1-secret"]-- def test_daemon_start_thread_resolves_profile_secret(self, scoped_embedded):- created, home = scoped_embedded- p = HindsightMemoryProvider()- p.initialize(session_id="s1", hermes_home=str(home), platform="cli")- for t in threading.enumerate():- if t.name == "hindsight-daemon-start":- t.join(timeout=5)- assert created == ["p1-secret"]- assert "Daemon started successfully" in (home / "logs" / "hindsight-embed.log").read_text()---def test_append_mode_trims_retained_turns_without_dropping_any(provider, monkeypatch):- """Append retains ship only the delta, so retained turns leave `_session_turns` (a never-ending- session no longer pins every turn) while every turn is still shipped exactly once."""- provider._auto_retain = True- provider._retain_every_n_turns = 3- monkeypatch.setattr(provider, "_ensure_writer", lambda: None)- monkeypatch.setattr(provider, "_register_atexit", lambda: None)- monkeypatch.setattr(provider, "_resolve_retain_target", lambda doc: ("doc", "append"))- shipped: list[str] = []- monkeypatch.setattr(provider, "_make_turn_retain_job",- lambda turns, **kw: (lambda: shipped.extend(turns)))- provider._retain_queue = MagicMock(put=lambda job: job())-- for i in range(7):- provider.sync_turn(f"user {i}", f"assistant {i}")-- assert len(provider._session_turns) == 1 # only the un-retained tail (turn 7)- assert provider._last_retained_turn_count == 0- assert len(shipped) == 6 and len(set(shipped)) == 6diff --git a/tests/plugins/memory/test_hindsight_templates.py b/tests/plugins/memory/test_hindsight_templates.pydeleted file mode 100644index bad225080b7..00000000000--- a/tests/plugins/memory/test_hindsight_templates.py+++ /dev/null@@ -1,260 +0,0 @@-"""Tests for the Hindsight setup-wizard starter-template step."""--import json-from contextlib import contextmanager--import pytest--from plugins.memory.hindsight import templates as tpl---_CATALOG = {- "templates": [- {"id": "conversation", "name": "Conversation", "integrations": ["litellm", "hermes"],- "manifest_file": "templates/conversation.json"},- {"id": "coding-agent", "name": "Coding Agent", "integrations": ["claude-code"],- "manifest_file": "templates/coding-agent.json"},- {"id": "hermes-gateway-bot", "name": "Gateway Bot", "integrations": ["hermes"],- "manifest_file": "templates/hermes-gateway-bot.json"},- ]-}---def test_fetch_hermes_templates_filters_to_hermes(monkeypatch):- monkeypatch.setattr(tpl, "_get_json", lambda url: _CATALOG)- entries = tpl.fetch_hermes_templates("https://example/templates.json")- ids = [e["id"] for e in entries]- assert ids == ["conversation", "hermes-gateway-bot"] # coding-agent excluded---def test_fetch_manifest_resolves_relative_url(monkeypatch):- seen = {}-- def _fake(url):- seen["url"] = url- return {"version": "1"}-- monkeypatch.setattr(tpl, "_get_json", _fake)- tpl.fetch_manifest(- {"manifest_file": "templates/hermes-gateway-bot.json"},- "https://raw.example/data/templates.json",- )- assert seen["url"] == "https://raw.example/data/templates/hermes-gateway-bot.json"---def test_apply_template_posts_to_import_endpoint(monkeypatch):- captured = {}-- @contextmanager- def _fake_open(req, timeout=None):- captured["url"] = req.full_url- captured["method"] = req.get_method()- captured["auth"] = req.get_header("Authorization")- captured["body"] = json.loads(req.data.decode("utf-8"))-- class _Resp:- def read(self):- return b""-- yield _Resp()-- monkeypatch.setattr(tpl, "open_credentialed_url", _fake_open)- tpl.apply_template("https://api.hindsight.vectorize.io/", "hermes", "hsk_abc", {"version": "1"})-- assert captured["url"] == "https://api.hindsight.vectorize.io/v1/default/banks/hermes/import"- assert captured["method"] == "POST"- assert captured["auth"] == "Bearer hsk_abc"- assert captured["body"] == {"version": "1"}---def test_apply_template_omits_auth_when_no_key(monkeypatch):- captured = {}-- @contextmanager- def _fake_open(req, timeout=None):- captured["auth"] = req.get_header("Authorization")-- class _Resp:- def read(self):- return b""-- yield _Resp()-- monkeypatch.setattr(tpl, "open_credentialed_url", _fake_open)- tpl.apply_template("http://localhost:8888", "hermes", None, {"version": "1"})- assert captured["auth"] is None---def _select_returning(idx):- def _select(title, items, default=0, cancel_returns=None):- return idx- return _select---def _select_seq(*returns):- it = iter(returns)-- def _select(title, items, default=0, cancel_returns=None):- return next(it)-- return _select---def test_supported_for_mode():- assert tpl.supported_for_mode("cloud") is True- assert tpl.supported_for_mode("local_external") is True- assert tpl.supported_for_mode("local_embedded") is False- assert tpl.supported_for_mode("local") is False---def test_run_template_step_applies_selected(monkeypatch):- monkeypatch.setattr(tpl, "fetch_hermes_templates", lambda url=None: [- {"id": "hermes-gateway-bot", "name": "Gateway Bot", "manifest_file": "templates/x.json"},- ])- monkeypatch.setattr(tpl, "fetch_manifest", lambda entry, url=None: {"version": "1"})- monkeypatch.setattr(tpl, "probe_existing_customization", lambda *a: False)- applied = {}- monkeypatch.setattr(tpl, "apply_template",- lambda api_url, bank_id, api_key, manifest: applied.update(bank=bank_id))-- result = tpl.run_template_step(- api_url="https://api", bank_id="hermes", api_key="k",- select=_select_returning(0), cancelled=-1, log=lambda *_: None,- )- assert result == "hermes-gateway-bot"- assert applied["bank"] == "hermes"---def test_run_template_step_blank_selection_skips(monkeypatch):- entries = [{"id": "hermes-gateway-bot", "name": "Gateway Bot", "manifest_file": "templates/x.json"}]- monkeypatch.setattr(tpl, "fetch_hermes_templates", lambda url=None: entries)- called = {"applied": False}- monkeypatch.setattr(tpl, "apply_template",- lambda *a, **k: called.update(applied=True))- # index len(entries) == the "Blank" row- result = tpl.run_template_step(- api_url="https://api", bank_id="hermes", api_key="k",- select=_select_returning(len(entries)), cancelled=-1, log=lambda *_: None,- )- assert result is None- assert called["applied"] is False---def test_run_template_step_no_templates_is_noop(monkeypatch):- monkeypatch.setattr(tpl, "fetch_hermes_templates", lambda url=None: [])- result = tpl.run_template_step(- api_url="https://api", bank_id="hermes", api_key="k",- select=_select_returning(0), cancelled=-1, log=lambda *_: None,- )- assert result is None---def test_run_template_step_swallows_fetch_errors(monkeypatch):- def _boom(url=None):- raise RuntimeError("network down")-- monkeypatch.setattr(tpl, "fetch_hermes_templates", _boom)- # must not raise- assert tpl.run_template_step(- api_url="https://api", bank_id="hermes", api_key="k",- select=_select_returning(0), cancelled=-1, log=lambda *_: None,- ) is None---def test_run_template_step_swallows_apply_errors(monkeypatch):- # gap 1: a failed apply (e.g. 401 for an OAuth-only user) must not crash setup.- import urllib.error-- monkeypatch.setattr(tpl, "fetch_hermes_templates", lambda url=None: [- {"id": "hermes-gateway-bot", "name": "Gateway Bot", "manifest_file": "templates/x.json"},- ])- monkeypatch.setattr(tpl, "fetch_manifest", lambda entry, url=None: {"version": "1"})- monkeypatch.setattr(tpl, "probe_existing_customization", lambda *a: False)-- def _raise(*a, **k):- raise urllib.error.HTTPError("u", 401, "Unauthorized", {}, None)-- monkeypatch.setattr(tpl, "apply_template", _raise)- logs = []- result = tpl.run_template_step(- api_url="https://api", bank_id="hermes", api_key=None,- select=_select_returning(0), cancelled=-1, log=logs.append,- )- assert result is None- assert any("Could not apply" in line for line in logs)---def _fake_open(payload):- @contextmanager- def _cm(req, timeout=None):- class _Resp:- def read(self):- return json.dumps(payload).encode("utf-8")-- yield _Resp()-- return _cm---def test_probe_existing_customization_true_when_bank_has_config(monkeypatch):- monkeypatch.setattr(tpl, "open_credentialed_url",- _fake_open({"version": "1", "bank": {"reflect_mission": "x"}}))- assert tpl.probe_existing_customization("https://api", "hermes", "k") is True---def test_probe_existing_customization_false_when_empty(monkeypatch):- monkeypatch.setattr(tpl, "open_credentialed_url",- _fake_open({"version": "1"}))- assert tpl.probe_existing_customization("https://api", "hermes", "k") is False---def test_probe_existing_customization_false_on_error(monkeypatch):- def _boom(req, timeout=None):- raise OSError("no bank")-- monkeypatch.setattr(tpl, "open_credentialed_url", _boom)- assert tpl.probe_existing_customization("https://api", "missing", None) is False---def _wire_apply(monkeypatch, customized):- monkeypatch.setattr(tpl, "fetch_hermes_templates", lambda url=None: [- {"id": "hermes-gateway-bot", "name": "Gateway Bot", "manifest_file": "templates/x.json"},- ])- monkeypatch.setattr(tpl, "fetch_manifest", lambda entry, url=None: {"version": "1"})- monkeypatch.setattr(tpl, "probe_existing_customization", lambda *a: customized)- called = {"applied": False}- monkeypatch.setattr(tpl, "apply_template", lambda *a, **k: called.update(applied=True))- return called---def test_warns_and_keeps_existing_when_declined(monkeypatch):- called = _wire_apply(monkeypatch, customized=True)- # first select = pick template (0); second select = confirm -> "Keep existing" (1)- result = tpl.run_template_step(- api_url="https://api", bank_id="hermes", api_key="k",- select=_select_seq(0, 1), cancelled=-1, log=lambda *_: None,- )- assert result is None- assert called["applied"] is False---def test_warns_then_applies_when_confirmed(monkeypatch):- called = _wire_apply(monkeypatch, customized=True)- # pick template (0), confirm "Apply" (0)- result = tpl.run_template_step(- api_url="https://api", bank_id="hermes", api_key="k",- select=_select_seq(0, 0), cancelled=-1, log=lambda *_: None,- )- assert result == "hermes-gateway-bot"- assert called["applied"] is True---def test_fresh_bank_skips_the_warning(monkeypatch):- called = _wire_apply(monkeypatch, customized=False)- # only ONE select call (no confirm) — _select_seq with a single value proves it- result = tpl.run_template_step(- api_url="https://api", bank_id="hermes", api_key="k",- select=_select_seq(0), cancelled=-1, log=lambda *_: None,- )- assert result == "hermes-gateway-bot"- assert called["applied"] is Truediff --git a/tests/plugins/memory/test_multiplex_memory_identity_scope.py b/tests/plugins/memory/test_multiplex_memory_identity_scope.pyindex b9a83b8350d..581a1f580e6 100644--- a/tests/plugins/memory/test_multiplex_memory_identity_scope.py+++ b/tests/plugins/memory/test_multiplex_memory_identity_scope.py@@ -2,7 +2,7 @@Under ``gateway.multiplex_profiles`` ``os.environ`` is the DEFAULT profile's ``.env``. When a secondaryprofile's scope does not define MEM0_USER_ID / SUPERMEMORY_CONTAINER_TAG / RETAINDB_PROJECT /-OPENVIKING_* / HINDSIGHT_BANK_ID / HERMES_HONCHO_HOST, the provider must fall back to its own default+OPENVIKING_* / HERMES_HONCHO_HOST, the provider must fall back to its own default(per-profile partition), NOT write the secondary's memories into the default profile's account."""from __future__ import annotations@@ -18,10 +18,6 @@ _DEFAULT_ENV = {"RETAINDB_PROJECT": "proj-default", "RETAINDB_BASE_URL": "https://rdb.default","OPENVIKING_API_KEY": "ov-default", "OPENVIKING_ACCOUNT": "acct-default", "OPENVIKING_USER": "user-default","OPENVIKING_AGENT": "agent-default", "OPENVIKING_ENDPOINT": "http://ov.default",- "HINDSIGHT_BANK_ID": "bank-default", "HINDSIGHT_MODE": "local_external", "HINDSIGHT_API_URL": "http://hs.default",- "HINDSIGHT_RETAIN_TAGS": "tag-default", "HINDSIGHT_RETAIN_OBSERVATION_SCOPES": "per_tag",- "HINDSIGHT_RETAIN_SOURCE": "source-default", "HINDSIGHT_RETAIN_USER_PREFIX": "UserDefault",- "HINDSIGHT_RETAIN_ASSISTANT_PREFIX": "AssistantDefault","HERMES_HONCHO_HOST": "host-default", "HONCHO_BASE_URL": "https://honcho.default","OPENAI_API_KEY": "sk-default", "OPENAI_BASE_URL": "https://openai.default/v1",}@@ -49,7 +45,6 @@ def secondary_profile(monkeypatch, tmp_path):def test_secondary_profile_memory_identity_never_inherits_default_environ(secondary_profile):- import plugins.memory.hindsight as hindsightimport plugins.memory.mem0 as mem0import plugins.memory.openviking as openvikingimport plugins.memory.retaindb as retaindb@@ -74,9 +69,6 @@ def test_secondary_profile_memory_identity_never_inherits_default_environ(secondclient = openviking._VikingClient("http://x", "k")assert (client._account, client._user) == ("default", "default") # the built-in tenant, not acct-default- hcfg = hindsight._load_config()- assert (hcfg["banks"]["hermes"]["bankId"], hcfg["mode"]) == ("hermes", "cloud")-assert honcho_client.resolve_active_host() != "host-default"assert honcho_client._env_base_url() is None@@ -97,58 +89,3 @@ def test_mem0_oss_llm_never_borrows_default_profile_openai_key(secondary_profilesecret_scope.reset_secret_scope(token)assert llm.client.api_key == "sk-b"assert str(llm.client.base_url).startswith("https://openai.b/v1")---def test_hindsight_retain_shaping_is_not_re_read_from_the_default_profile_environ(secondary_profile):- """The provider must retain with ITS OWN shaping, not the default profile's.-- ``_load_config`` resolves retain shaping through the secret scope, but the values it produces- pass through ``_apply_retain_settings``, whose ``cfg_or_env`` half re-read ``os.environ`` — so- every scoped miss came back as the default profile's tag, scope, source and speaker prefixes.- ``metadata.source`` is opt-in by AGENTS.md, and tags are the retrieval partition, so a secondary- profile's memories were both mislabelled and selectable by the default profile's tag filters.- """- import plugins.memory.hindsight as hindsight- from plugins.memory.hindsight.settings import _DEFAULT_RETAIN_SOURCE-- cfg = hindsight._load_config()- assert (cfg["retain_source"], cfg["retain_user_prefix"], cfg["retain_assistant_prefix"]) == (- _DEFAULT_RETAIN_SOURCE, "User", "Assistant")-- provider = hindsight.HindsightMemoryProvider()- provider._apply_retain_settings(cfg)- assert provider._retain_tags == []- assert provider._observation_scopes is None- assert provider._retain_source == _DEFAULT_RETAIN_SOURCE- assert (provider._retain_user_prefix, provider._retain_assistant_prefix) == ("User", "Assistant")-- # A config.json install never reaches ``_load_config``'s scoped read at all, so the fallback- # inside ``_apply_retain_settings`` is the only gate for it.- provider._apply_retain_settings({})- assert provider._retain_tags == []- assert provider._retain_source == _DEFAULT_RETAIN_SOURCE-- # The profile's OWN scoped values still win — this is isolation, not a blindfold.- token = secret_scope.set_secret_scope({"HINDSIGHT_RETAIN_TAGS": "tag-b", "HINDSIGHT_RETAIN_SOURCE": "source-b"})- try:- provider._apply_retain_settings({})- finally:- secret_scope.reset_secret_scope(token)- assert provider._retain_tags == ["tag-b"]- assert provider._retain_source == "source-b"---def test_hindsight_retain_shaping_still_reads_the_process_env_for_a_single_profile(monkeypatch, tmp_path):- """No multiplexing: the process env IS this profile's own .env, so it must keep being read."""- import plugins.memory.hindsight as hindsight-- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- monkeypatch.setenv("HINDSIGHT_RETAIN_TAGS", "solo-tag")- monkeypatch.setenv("HINDSIGHT_RETAIN_SOURCE", "solo-source")- monkeypatch.setenv("HINDSIGHT_RETAIN_USER_PREFIX", "Operator")-- provider = hindsight.HindsightMemoryProvider()- provider._apply_retain_settings({})- assert provider._retain_tags == ["solo-tag"]- assert provider._retain_source == "solo-source"- assert provider._retain_user_prefix == "Operator"diff --git a/tests/plugins/memory/test_provider_threads_inherit_profile.py b/tests/plugins/memory/test_provider_threads_inherit_profile.pyindex efb127452f1..252cda49831 100644--- a/tests/plugins/memory/test_provider_threads_inherit_profile.py+++ b/tests/plugins/memory/test_provider_threads_inherit_profile.py@@ -72,16 +72,6 @@ def _openviking(seen, tmp_path):return list(workers)-def _hindsight(seen, tmp_path):- import plugins.memory.hindsight as hindsight-- p = hindsight.HindsightMemoryProvider()- p._recall_sync, p._memory_mode, p._auto_recall, p._prefetch_waits_for_retain = False, "hybrid", True, False- p._do_recall = lambda query: (seen.setdefault("home", get_hermes_home()) and "text", 1)- p.queue_prefetch("remember this")- return [p._prefetch_thread]--def _honcho(seen, tmp_path):from plugins.memory.honcho import HonchoMemoryProvider@@ -90,7 +80,7 @@ def _honcho(seen, tmp_path):_PROVIDERS = {"mem0": _mem0, "retaindb": _retaindb, "byterover": _byterover, "supermemory": _supermemory,- "openviking": _openviking, "hindsight": _hindsight, "honcho": _honcho,+ "openviking": _openviking, "honcho": _honcho,}diff --git a/tests/plugins/test_hindsight_health_grace_timeout.py b/tests/plugins/test_hindsight_health_grace_timeout.pydeleted file mode 100644index 0e068d12710..00000000000--- a/tests/plugins/test_hindsight_health_grace_timeout.py+++ /dev/null@@ -1,64 +0,0 @@-"""Embedded-daemon health grace timeout export (issue #13125 comment thread).--On resource-contended hosts the embedded Hindsight daemon can exceed a single-2s /health check and get needlessly killed + restarted. Upstream exposes the-grace window via HINDSIGHT_EMBED_PORT_HEALTH_GRACE_TIMEOUT (read at import-time). The plugin surfaces it as a config.json knob and exports it to the-process env BEFORE daemon_embed_manager is imported.-"""--import importlib--import pytest--hindsight = importlib.import_module("plugins.memory.hindsight")-_export = hindsight._export_port_health_grace_timeout-_ENV = importlib.import_module("plugins.memory.hindsight.embedded")._PORT_HEALTH_GRACE_ENV--[email protected](autouse=True)-def _clear_env(monkeypatch):- monkeypatch.delenv(_ENV, raising=False)---def test_configured_value_exported(monkeypatch):- _export({"port_health_grace_timeout": 60})- import os-- assert float(os.environ[_ENV]) == 60.0---def test_string_value_parsed(monkeypatch):- _export({"port_health_grace_timeout": "45"})- import os-- assert float(os.environ[_ENV]) == 45.0---def test_blank_and_missing_are_noops(monkeypatch):- import os-- _export({})- assert _ENV not in os.environ- _export({"port_health_grace_timeout": ""})- assert _ENV not in os.environ- _export({"port_health_grace_timeout": None})- assert _ENV not in os.environ---def test_invalid_and_negative_ignored(monkeypatch):- import os-- _export({"port_health_grace_timeout": "not-a-number"})- assert _ENV not in os.environ- _export({"port_health_grace_timeout": -5})- assert _ENV not in os.environ---def test_explicit_env_wins_over_config(monkeypatch):- import os-- monkeypatch.setenv(_ENV, "99")- _export({"port_health_grace_timeout": 60})- # setdefault must not clobber an operator-set env override.- assert os.environ[_ENV] == "99"diff --git a/tests/plugins/test_hindsight_root_guard.py b/tests/plugins/test_hindsight_root_guard.pydeleted file mode 100644index 18db639ceac..00000000000--- a/tests/plugins/test_hindsight_root_guard.py+++ /dev/null@@ -1,102 +0,0 @@-"""Root-user guard for Hindsight local_embedded mode (issue #13125).--PostgreSQL's initdb refuses to run as root, so the embedded Hindsight daemon-can never initialize under root — without a guard it crash-restart loops-forever, burning RAM/CPU with no user-visible error. initialize() must detect-root up front, skip daemon startup, disable the provider, and warn the user.-"""--import importlib-import threading--import pytest--hindsight = importlib.import_module("plugins.memory.hindsight")-HindsightMemoryProvider = hindsight.HindsightMemoryProvider---def _make_local_embedded_provider(monkeypatch):- """Build a provider wired for local_embedded with a passing runtime probe."""- monkeypatch.setattr(- hindsight,- "_load_config",- lambda: {"mode": "local_embedded", "profile": "hermes"},- )- # Pretend the local runtime imports cleanly so initialize() reaches the- # daemon-start branch instead of bailing on a missing `hindsight` package.- monkeypatch.setattr(hindsight, "_check_local_runtime", lambda: (True, None))- return HindsightMemoryProvider()---def _daemon_threads_alive() -> list[str]:- return [t.name for t in threading.enumerate() if t.name == "hindsight-daemon-start"]---def test_local_embedded_skips_daemon_as_root(monkeypatch, caplog):- """As root, the daemon thread must NOT start and the mode is disabled."""- provider = _make_local_embedded_provider(monkeypatch)- monkeypatch.setattr(hindsight.os, "geteuid", lambda: 0, raising=False)-- # If the guard fails, _start_daemon would call _get_client() — make that- # explode so a regression is loud rather than silently spawning a thread.- monkeypatch.setattr(- provider,- "_get_client",- lambda: pytest.fail("daemon startup attempted while running as root"),- )-- before = set(_daemon_threads_alive())- with caplog.at_level("WARNING", logger="plugins.memory.hindsight"):- provider.initialize(session_id="s1")-- assert provider._mode == "disabled"- assert set(_daemon_threads_alive()) == before # no new daemon thread- # The warning is surfaced to the user via the logger AND printed to- # stderr (E2E-verified in tests/plugins/test_hindsight_root_guard.py- # docstring rationale); capsys can't reliably capture the module-level- # sys.stderr write under the isolation harness, so assert on the log.- assert any("cannot run as root" in r.message for r in caplog.records)---def _fake_thread_factory(started: threading.Event):- """Return a Thread replacement that records start() without running work."""- real_thread = threading.Thread-- def _factory(*args, **kwargs):- if kwargs.get("name") == "hindsight-daemon-start":- started.set()-- class _NoopThread:- def start(self):- pass-- return _NoopThread()- return real_thread(*args, **kwargs)-- return _factory---def test_root_warning_uses_gated_warning_callback_when_wired(monkeypatch, capsys):- """CLI wiring passes agent._emit_warning: the notice goes through that gated sink, not raw stderr."""- provider = _make_local_embedded_provider(monkeypatch)- monkeypatch.setattr(hindsight.os, "geteuid", lambda: 0, raising=False)- seen = []- provider.initialize(session_id="s1", warning_callback=seen.append, platform="cli")- assert provider._mode == "disabled"- assert len(seen) == 1 and "cannot run as root" in seen[0]- assert "cannot run as root" not in capsys.readouterr().err--[email protected]("setting", (None, False, True))-def test_root_warning_stderr_fallback_honors_policy(tmp_path, monkeypatch, capsys, setting):- """No warning_callback (gateway/TUI wiring): the stderr fallback follows the shared boundary;- the logger.warning is always recorded."""- import json- home = tmp_path / f"home-{setting}"; home.mkdir()- monkeypatch.setenv("HERMES_HOME", str(home))- (home / "config.yaml").write_text(json.dumps({"display": {} if setting is None else {"suppress_warning_notifications": setting}}))- provider = _make_local_embedded_provider(monkeypatch)- monkeypatch.setattr(hindsight.os, "geteuid", lambda: 0, raising=False)- provider.initialize(session_id="s1", platform="cli")- assert provider._mode == "disabled"- assert ("cannot run as root" in capsys.readouterr().err) is (setting is not True)diff --git a/tests/tools/test_lazy_deps.py b/tests/tools/test_lazy_deps.pyindex 32a082636cd..38b37eda59d 100644--- a/tests/tools/test_lazy_deps.py+++ b/tests/tools/test_lazy_deps.py@@ -225,20 +225,19 @@ class TestIsSatisfiedVersionAware:def test_plugin_owned_sdk_newer_compatible_release_is_satisfied(self, monkeypatch):"""A newer release inside the plugin.yaml range must not be re-pinned downward on refresh- (#86992 hindsight-client 0.9.x -> 0.6.1, #98407 mem0ai 2.0.19 -> 2.0.10)."""- self._fake_version(monkeypatch, {"hindsight-client": "0.9.2", "mem0ai": "2.0.19"})- assert ld.feature_missing("memory.hindsight") == ()+ (#98407 mem0ai 2.0.19 -> 2.0.10; the same class hit the former hindsight extra, #86992)."""+ self._fake_version(monkeypatch, {"mem0ai": "2.0.19"})assert ld.feature_missing("memory.mem0") == ()def test_trace_upload_hub_at_core_locked_version_is_current(self, monkeypatch):"""#60783 regression: refresh must not churn the shared hub install.huggingface-hub arrives in the venv via the core lock (transformers /- sentence-transformers for local Hindsight, faster-whisper, tokenizers).+ sentence-transformers for local memory-plugin embeddings, faster-whisper, tokenizers).With the LAZY_DEPS pin held in lockstep with uv.lock, the version thecore installs satisfies the trace-upload spec, so the `hermes update`lazy-refresh pass reports "current" instead of reinstalling — the- downgrade that used to break the Hindsight daemon can't happen.+ downgrade that used to break embedding daemons (#60783) can't happen."""spec = ld.LAZY_DEPS["tool.trace_upload"][0]pinned = ld._specifier_from_spec(spec).lstrip("=")