Skip to content

The agent that grows with you

refactor(plugins/memory): holographic/supermemory/retaindb/byterover — action dispatch tables, unified HTTP helpers, dead code removal; provider registry dedupe

Teknium57c35858e341
diff --git a/plugins/memory/__init__.py b/plugins/memory/__init__.py
index a24029a0de3..7b6b31c46ef 100644
--- a/plugins/memory/__init__.py
+++ b/plugins/memory/__init__.py
@@ -31,15 +31,15 @@ Usage:
from __future__ import annotations
-import importlib
-import importlib.machinery
import importlib.metadata
import importlib.util
import logging
import sys
from pathlib import Path
from typing import List, Optional, Tuple, TYPE_CHECKING
+
from hermes_cli.config import cfg_get
+from plugins import plugin_loader as _loader
if TYPE_CHECKING:
from agent.memory_provider import MemoryProvider
@@ -54,39 +54,14 @@ _REGISTERED_MEMORY_PROVIDER_SKILLS: dict[str, Path] = {}
# collide with bundled providers in sys.modules.
_USER_NAMESPACE = "_hermes_user_memory"
-
-def _register_synthetic_package(name: str, search_locations: List[str]) -> None:
- """Register an empty package shell in sys.modules.
-
- User-installed providers import as ``_hermes_user_memory.<name>``, a
- dotted name whose parents exist nowhere on disk. Unless those parents
- are present in ``sys.modules``, any relative import inside the plugin
- (``from . import config``) fails with
- ``ModuleNotFoundError: No module named '_hermes_user_memory'`` — the
- same reason the loader already registers ``plugins`` and
- ``plugins.memory`` for bundled providers.
- """
- if name in sys.modules:
- return
- spec = importlib.machinery.ModuleSpec(name, None, is_package=True)
- spec.submodule_search_locations = search_locations
- sys.modules[name] = importlib.util.module_from_spec(spec)
+_register_synthetic_package = _loader.register_synthetic_package
+_get_user_plugins_dir = _loader.user_plugins_dir
# ---------------------------------------------------------------------------
# Directory helpers
# ---------------------------------------------------------------------------
-def _get_user_plugins_dir() -> Optional[Path]:
- """Return ``$HERMES_HOME/plugins/`` or None if unavailable."""
- try:
- from hermes_constants import get_hermes_home
- d = get_hermes_home() / "plugins"
- return d if d.is_dir() else None
- except Exception:
- return None
-
-
def _get_project_plugins_dir() -> Optional[Path]:
"""Return ``./.hermes/plugins/`` or None if unavailable or not opted in.
@@ -106,11 +81,7 @@ def _get_project_plugins_dir() -> Optional[Path]:
def _is_memory_provider_dir(path: Path) -> bool:
- """Heuristic: does *path* look like a memory provider plugin?
-
- Checks for ``register_memory_provider`` or ``MemoryProvider`` in the
- ``__init__.py`` source. Cheap text scan — no import needed.
- """
+ """Cheap text heuristic (no import): ``__init__.py`` mentions the memory provider contract."""
init_file = path / "__init__.py"
if not init_file.exists():
return False
@@ -121,40 +92,31 @@ def _is_memory_provider_dir(path: Path) -> bool:
return False
-def _iter_provider_dirs() -> List[Tuple[str, Path]]:
- """Yield ``(name, path)`` for all discovered provider directories.
+def _is_bundled(provider_dir: Path) -> bool:
+ return _MEMORY_PLUGINS_DIR in provider_dir.parents or provider_dir.parent == _MEMORY_PLUGINS_DIR
- Scans bundled, then user-installed, then project-local. Bundled takes
- precedence on name collisions (first-seen wins via ``seen`` set).
- """
- seen: set = set()
- dirs: List[Tuple[str, Path]] = []
-
- # 1. Bundled providers (plugins/memory/<name>/)
- if _MEMORY_PLUGINS_DIR.is_dir():
- for child in sorted(_MEMORY_PLUGINS_DIR.iterdir()):
- if not child.is_dir() or child.name.startswith(("_", ".")):
- continue
- if not (child / "__init__.py").exists():
- continue
- seen.add(child.name)
- dirs.append((child.name, child))
-
- # 2. User-installed providers ($HERMES_HOME/plugins/<name>/)
- # 3. Project-local providers (./.hermes/plugins/<name>/), opt-in
+
+def _module_name(provider_dir: Path, name: str) -> str:
+ """``plugins.memory.<name>`` for bundled providers, else under the synthetic user namespace."""
+ return f"plugins.memory.{name}" if _is_bundled(provider_dir) else f"{_USER_NAMESPACE}.{name}"
+
+
+def _iter_provider_dirs() -> List[Tuple[str, Path]]:
+ """``(name, path)`` for bundled, then user-installed, then project-local; first-seen wins."""
+ dirs = [(child.name, child) for child in _loader.iter_plugin_dirs(_MEMORY_PLUGINS_DIR)]
+ seen = {name for name, _ in dirs}
for source_dir in (_get_user_plugins_dir(), _get_project_plugins_dir()):
if not source_dir:
continue
for child in sorted(source_dir.iterdir()):
- if not child.is_dir() or child.name.startswith(("_", ".")):
- continue
- if child.name in seen:
- continue # earlier source wins
- if not _is_memory_provider_dir(child):
- continue # skip non-memory plugins
- seen.add(child.name)
- dirs.append((child.name, child))
-
+ if (
+ child.is_dir()
+ and not child.name.startswith(("_", "."))
+ and child.name not in seen
+ and _is_memory_provider_dir(child)
+ ):
+ seen.add(child.name)
+ dirs.append((child.name, child))
return dirs
@@ -173,47 +135,38 @@ def _iter_entry_points():
def find_provider_dir(name: str) -> Optional[Path]:
- """Resolve a provider name to the directory holding its files.
+ """Resolve a provider name to its directory: bundled, user, project, then the
+ package directory of a pip entry-point provider.
- Checks bundled, then user-installed, then project-local, then the package
- directory of a pip entry-point provider.
-
- The entry-point case matters because two of a provider's files are read
- from disk rather than imported: ``config_schema.py`` (loaded by path so the
- web server never pulls in the agent runtime — see
- ``plugins/memory/config_schema.py``) and ``cli.py`` (loaded by
- ``discover_plugin_cli_commands`` at argparse time). Without a directory, a
+ The entry-point case matters because two of a provider's files are read from
+ disk rather than imported: ``config_schema.py`` (loaded by path so the web
+ server never pulls in the agent runtime) and ``cli.py`` (loaded by
+ ``discover_plugin_cli_commands`` at argparse time). Without a directory a
pip-installed provider silently loses its dashboard config panel and its
- ``hermes <provider>`` subcommands — working, but a second-class citizen next
- to a directory install.
+ ``hermes <provider>`` subcommands.
"""
- # Bundled
bundled = _MEMORY_PLUGINS_DIR / name
if bundled.is_dir() and (bundled / "__init__.py").exists():
return bundled
- # User-installed, then project-local
for source_dir in (_get_user_plugins_dir(), _get_project_plugins_dir()):
if not source_dir:
continue
candidate = source_dir / name
if candidate.is_dir() and _is_memory_provider_dir(candidate):
return candidate
- # Pip entry point
return _entry_point_package_dir(find_provider_entry_point(name))
def _entry_point_package_dir(entry_point) -> Optional[Path]:
"""The directory of an entry point's module, resolved WITHOUT importing it.
- Discovery must stay free of third-party imports: ``find_provider_dir`` is
- called from the dashboard and from argparse setup, long before the operator
- has selected a provider, so importing every installed candidate would run
- arbitrary code on the strength of a package merely being present.
- ``resolve_module_origin`` walks the module's file layout instead.
+ Discovery must stay free of third-party imports: ``find_provider_dir`` runs
+ from the dashboard and argparse setup, long before the operator has selected
+ a provider, so importing every installed candidate would run arbitrary code
+ on the strength of a package merely being present.
- Only package entry points (``pkg/__init__.py``) yield a directory — a
- provider pointed at a bare ``module.py`` has nowhere to put a sibling
- ``config_schema.py``, so it correctly resolves to None.
+ Only package entry points (``pkg/__init__.py``) yield a directory — a bare
+ ``module.py`` has nowhere to put a sibling ``config_schema.py``.
"""
if entry_point is None:
return None
@@ -234,10 +187,7 @@ def _entry_point_package_dir(entry_point) -> Optional[Path]:
def find_provider_entry_point(name: str):
"""Resolve a provider name to a pip entry point, if installed."""
- for entry_point in _iter_entry_points():
- if entry_point.name == name:
- return entry_point
- return None
+ return next((ep for ep in _iter_entry_points() if ep.name == name), None)
# ---------------------------------------------------------------------------
@@ -245,13 +195,9 @@ def find_provider_entry_point(name: str):
# ---------------------------------------------------------------------------
def list_memory_provider_names() -> List[str]:
- """Cheap name-only listing of discoverable memory providers.
-
- Unlike :func:`discover_memory_providers`, this does NOT import provider
- modules or run availability checks — a directory scan plus entry-point
- *enumeration*, which reads distribution metadata without executing any of
- it. Safe to call at module-import time (e.g. when building the dashboard
- config schema, where it fills the ``memory.provider`` dropdown).
+ """Cheap name-only listing: directory scan plus entry-point *enumeration*
+ (distribution metadata only — no provider import, no availability check),
+ so it is safe at module-import time (dashboard ``memory.provider`` dropdown).
"""
names = {name for name, _ in _iter_provider_dirs()}
names.update(ep.name for ep in _iter_entry_points())
@@ -259,63 +205,25 @@ def list_memory_provider_names() -> List[str]:
def discover_memory_providers() -> List[Tuple[str, str, bool]]:
- """Scan directory and pip entry-point memory providers.
-
- Returns list of (name, description, is_available) tuples.
- Bundled providers take precedence on name collisions, followed by
- user-installed directory providers, then pip entry-point providers.
- """
+ """``[(name, description, is_available), ...]`` for directory then entry-point
+ providers; bundled wins on name collisions, then user directories, then pip."""
results = []
- seen: set[str] = set()
-
for name, child in _iter_provider_dirs():
- # Read description from plugin.yaml if available
- desc = ""
- yaml_file = child / "plugin.yaml"
- if yaml_file.exists():
- try:
- import yaml
- with open(yaml_file, encoding="utf-8-sig") as f:
- meta = yaml.safe_load(f) or {}
- desc = meta.get("description", "")
- except Exception:
- pass
-
- # Quick availability check — try loading and calling is_available()
- available = True
- try:
- provider = _load_provider_from_dir(child, register_skills=False)
- if provider:
- available = provider.is_available()
- else:
- available = False
- except Exception:
- available = False
-
- results.append((name, desc, available))
- seen.add(name)
-
+ results.append((
+ name,
+ _loader.read_plugin_description(child),
+ _loader.probe_availability(lambda c=child: _load_provider_from_dir(c, register_skills=False)),
+ ))
+ seen = {name for name, _, _ in results}
for entry_point in _iter_entry_points():
- name = entry_point.name
- if name in seen:
- continue
- desc = ""
- available = True
- try:
- provider = _load_provider_from_entry_point(
- entry_point,
- register_skills=False,
- )
- if provider:
- available = provider.is_available()
- else:
- available = False
- except Exception:
- available = False
-
- results.append((name, desc, available))
- seen.add(name)
-
+ if entry_point.name not in seen:
+ seen.add(entry_point.name)
+ results.append((
+ entry_point.name, "",
+ _loader.probe_availability(
+ lambda ep=entry_point: _load_provider_from_entry_point(ep, register_skills=False)
+ ),
+ ))
return results
@@ -324,15 +232,11 @@ def load_memory_provider(
*,
register_skills: Optional[bool] = None,
) -> Optional["MemoryProvider"]:
- """Load and return a MemoryProvider instance by name.
-
- Checks bundled (``plugins/memory/<name>/``), user-installed
- (``$HERMES_HOME/plugins/<name>/``), and pip entry-point providers.
- Bundled providers take precedence on name collisions.
+ """Load a MemoryProvider by name (bundled, user, project, then pip entry point).
Skills register only when *name* is the configured active provider unless
- ``register_skills`` is passed explicitly. This keeps status and setup
- inspection of inactive providers free of registry side effects.
+ ``register_skills`` is passed explicitly, so status/setup inspection of
+ inactive providers leaves no registry side effects.
Returns None if the provider is not found or fails to load.
"""
@@ -348,22 +252,29 @@ def load_memory_provider(
)
return None
- try:
- provider = (
- _load_provider_from_dir(provider_dir, register_skills=register_skills)
- if provider_dir
- else _load_provider_from_entry_point(
- entry_point,
- register_skills=register_skills,
- )
- )
- if provider:
- return provider
- logger.warning("Memory provider '%s' loaded but no provider instance found", name)
- return None
- except Exception as e:
- logger.warning("Failed to load memory provider '%s': %s", name, e)
- return None
+ def _load(_dir):
+ if provider_dir:
+ return _load_provider_from_dir(provider_dir, register_skills=register_skills)
+ return _load_provider_from_entry_point(entry_point, register_skills=register_skills)
+
+ return _loader.load_named(
+ name, provider_dir, _load, kind="Memory provider", noun="provider", logger=logger,
+ )
+
+
+def _instantiate_subclass(namespace) -> Optional["MemoryProvider"]:
+ """First instantiable ``MemoryProvider`` subclass found among *namespace*'s attributes."""
+ from agent.memory_provider import MemoryProvider
+
+ for attr_name in dir(namespace):
+ attr = getattr(namespace, attr_name, None)
+ if (isinstance(attr, type) and issubclass(attr, MemoryProvider)
+ and attr is not MemoryProvider):
+ try:
+ return attr()
+ except Exception:
+ pass
+ return None
def _load_provider_from_entry_point(
@@ -403,17 +314,10 @@ def _load_provider_from_entry_point(
loaded(collector)
return collector.provider
- for attr_name in dir(loaded):
- attr = getattr(loaded, attr_name, None)
- if (isinstance(attr, type) and issubclass(attr, MemoryProvider)
- and attr is not MemoryProvider):
- try:
- return attr()
- except Exception:
- pass
-
- logger.debug("Memory provider entry point '%s' loaded no provider", entry_point.name)
- return None
+ provider = _instantiate_subclass(loaded)
+ if provider is None:
+ logger.debug("Memory provider entry point '%s' loaded no provider", entry_point.name)
+ return provider
def _load_provider_from_dir(
@@ -421,93 +325,18 @@ def _load_provider_from_dir(
*,
register_skills: bool = True,
) -> Optional["MemoryProvider"]:
- """Import a provider module and extract the MemoryProvider instance.
-
- The module must have either:
- - A register(ctx) function (plugin-style) — we simulate a ctx
- - A top-level class that extends MemoryProvider — we instantiate it
- """
+ """Import a provider module and extract its MemoryProvider: ``register(ctx)``
+ first (how our plugins are written), else instantiate a top-level subclass."""
name = provider_dir.name
- # Use a separate namespace for user-installed plugins so they don't
- # collide with bundled providers in sys.modules.
- _is_bundled = _MEMORY_PLUGINS_DIR in provider_dir.parents or provider_dir.parent == _MEMORY_PLUGINS_DIR
- module_name = f"plugins.memory.{name}" if _is_bundled else f"{_USER_NAMESPACE}.{name}"
- init_file = provider_dir / "__init__.py"
-
- if not init_file.exists():
+ mod = _loader.load_plugin_module(
+ _module_name(provider_dir, name), provider_dir,
+ parents=("plugins", "plugins.memory"),
+ logger=logger,
+ synthetic_namespace=None if _is_bundled(provider_dir) else _USER_NAMESPACE,
+ )
+ if mod is None:
return None
- # Check if already loaded. A synthetic package shell registered by
- # discover_plugin_cli_commands() for relative-import support has no
- # __file__; only reuse modules that were actually loaded from disk.
- cached = sys.modules.get(module_name)
- if cached is not None and getattr(cached, "__file__", None):
- mod = cached
- else:
- # Handle relative imports within the plugin
- # First ensure the parent packages are registered
- for parent in ("plugins", "plugins.memory"):
- if parent not in sys.modules:
- parent_path = Path(__file__).parent
- if parent == "plugins":
- parent_path = parent_path.parent
- parent_init = parent_path / "__init__.py"
- if parent_init.exists():
- spec = importlib.util.spec_from_file_location(
- parent, str(parent_init),
- submodule_search_locations=[str(parent_path)]
- )
- if spec:
- parent_mod = importlib.util.module_from_spec(spec)
- sys.modules[parent] = parent_mod
- try:
- spec.loader.exec_module(parent_mod)
- except Exception:
- pass
-
- # User-installed plugins need their synthetic parent registered the
- # same way, or relative imports inside the plugin cannot resolve.
- if not _is_bundled:
- _register_synthetic_package(_USER_NAMESPACE, [])
-
- # Now load the provider module
- spec = importlib.util.spec_from_file_location(
- module_name, str(init_file),
- submodule_search_locations=[str(provider_dir)]
- )
- if not spec:
- return None
-
- mod = importlib.util.module_from_spec(spec)
- sys.modules[module_name] = mod
-
- # Register submodules so relative imports work
- # e.g., "from .store import MemoryStore" in holographic plugin
- for sub_file in provider_dir.glob("*.py"):
- if sub_file.name == "__init__.py":
- continue
- sub_name = sub_file.stem
- full_sub_name = f"{module_name}.{sub_name}"
- if full_sub_name not in sys.modules:
- sub_spec = importlib.util.spec_from_file_location(
- full_sub_name, str(sub_file)
- )
- if sub_spec:
- sub_mod = importlib.util.module_from_spec(sub_spec)
- sys.modules[full_sub_name] = sub_mod
- try:
- sub_spec.loader.exec_module(sub_mod)
- except Exception as e:
- logger.debug("Failed to load submodule %s: %s", full_sub_name, e)
-
- try:
- spec.loader.exec_module(mod)
- except Exception as e:
- logger.debug("Failed to exec_module %s: %s", module_name, e)
- sys.modules.pop(module_name, None)
- return None
-
- # Try register(ctx) pattern first (how our plugins are written)
if hasattr(mod, "register"):
collector = _ProviderCollector(name, register_skills=register_skills)
try:
@@ -528,18 +357,7 @@ def _load_provider_from_dir(
if collector.provider:
return collector.provider
- # Fallback: find a MemoryProvider subclass and instantiate it
- from agent.memory_provider import MemoryProvider
- for attr_name in dir(mod):
- attr = getattr(mod, attr_name, None)
- if (isinstance(attr, type) and issubclass(attr, MemoryProvider)
- and attr is not MemoryProvider):
- try:
- return attr()
- except Exception:
- pass
-
- return None
+ return _instantiate_subclass(mod)
class _ProviderCollector:
@@ -594,19 +412,11 @@ class _ProviderCollector:
def __getattr__(self, attr: str):
"""Delegate any other ``register_*`` call to a real ``PluginContext``.
- Memory providers used to get a hand-maintained stub of three no-ops
- here, which had two failure modes. Calls it *did* know about
- (``register_tool``, ``register_hook``) were silently dropped, so a
- provider's tools simply never appeared. Calls it did *not* know about
- raised ``AttributeError`` — and ``register_auxiliary_task`` is one of
- them, despite ``PluginContext.register_auxiliary_task`` documenting a
- memory provider (hindsight's pre-retain dedup) as its worked example.
- That exception surfaces as "register() failed" and costs the provider.
-
- Delegating instead of enumerating means this can never drift behind
- ``PluginContext`` again: a capability added there works for memory
- providers on the same commit, which is what the "widen the generic
- plugin surface" rule in AGENTS.md asks for.
+ A hand-maintained stub used to silently drop calls it knew
+ (``register_tool``, ``register_hook``) and raise ``AttributeError`` on
+ ones it didn't (``register_auxiliary_task``), which surfaced as
+ "register() failed" and cost the provider. Delegating means this can
+ never drift behind ``PluginContext`` again.
Only ``register_*`` is forwarded. Everything else raises normally, so a
typo still fails loudly rather than being absorbed.
@@ -644,12 +454,7 @@ class _ProviderCollector:
def _get_active_memory_provider() -> Optional[str]:
- """Read the active memory provider name from config.yaml.
-
- Returns the provider name (e.g. ``"honcho"``) or None if no
- external provider is configured. Lightweight — only reads config,
- no plugin loading.
- """
+ """Active provider name from config.yaml (``memory.provider``), or None. Reads config only."""
try:
from hermes_cli.config import load_config
config = load_config()
@@ -680,21 +485,12 @@ def _prune_inactive_memory_provider_skills(
def discover_plugin_cli_commands() -> List[dict]:
- """Return CLI commands for the **active** memory plugin only.
+ """CLI commands for the **active** memory plugin only (``memory.provider``).
- Only one memory provider can be active at a time (set via
- ``memory.provider`` in config.yaml). This function reads that
- value and only loads CLI registration for the matching plugin.
- If no provider is active, no commands are registered.
-
- Looks for a ``register_cli(subparser)`` function in the active
- plugin's ``cli.py``. Returns a list of at most one dict with
- keys: ``name``, ``help``, ``description``, ``setup_fn``,
- ``handler_fn``.
-
- This is a lightweight scan — it only imports ``cli.py``, not the
- full plugin module. Safe to call during argparse setup before
- any provider is loaded.
+ Lightweight: imports only the active plugin's ``cli.py`` (looking for
+ ``register_cli(subparser)``), never the provider module, so it is safe during
+ argparse setup. Returns at most one dict with keys ``name``, ``help``,
+ ``description``, ``setup_fn``, ``handler_fn``, ``plugin``.
"""
results: List[dict] = []
if not _MEMORY_PLUGINS_DIR.is_dir():
@@ -704,7 +500,6 @@ def discover_plugin_cli_commands() -> List[dict]:
if not active_provider:
return results
- # Only look at the active provider's directory
plugin_dir = find_provider_dir(active_provider)
if not plugin_dir:
return results
@@ -713,28 +508,22 @@ def discover_plugin_cli_commands() -> List[dict]:
if not cli_file.exists():
return results
- _is_bundled = _MEMORY_PLUGINS_DIR in plugin_dir.parents or plugin_dir.parent == _MEMORY_PLUGINS_DIR
- module_name = f"plugins.memory.{active_provider}.cli" if _is_bundled else f"{_USER_NAMESPACE}.{active_provider}.cli"
+ module_name = _module_name(plugin_dir, active_provider) + ".cli"
try:
- # Import the CLI module (lightweight — no SDK needed)
if module_name in sys.modules:
cli_mod = sys.modules[module_name]
else:
- if not _is_bundled:
- # cli.py imports as _hermes_user_memory.<name>.cli, usually
- # before the provider itself is loaded. Register its parent
- # packages so relative imports inside cli.py
- # ("from . import config") resolve without executing the
- # plugin's __init__.py. The package shell has no __file__,
- # so _load_provider_from_dir() will still load the real
- # module later instead of reusing the shell.
+ if not _is_bundled(plugin_dir):
+ # cli.py imports as _hermes_user_memory.<name>.cli, usually before
+ # the provider itself is loaded. Register its parent packages so
+ # relative imports inside cli.py resolve without executing the
+ # plugin's __init__.py. The shell has no __file__, so
+ # _load_provider_from_dir() still loads the real module later.
_register_synthetic_package(_USER_NAMESPACE, [])
_register_synthetic_package(
f"{_USER_NAMESPACE}.{active_provider}", [str(plugin_dir)]
)
- spec = importlib.util.spec_from_file_location(
- module_name, str(cli_file)
- )
+ spec = importlib.util.spec_from_file_location(module_name, str(cli_file))
if not spec or not spec.loader:
return results
cli_mod = importlib.util.module_from_spec(spec)
@@ -745,29 +534,14 @@ def discover_plugin_cli_commands() -> List[dict]:
if not callable(register_cli):
return results
- # Read metadata from plugin.yaml if available
- help_text = f"Manage {active_provider} memory plugin"
- description = ""
- yaml_file = plugin_dir / "plugin.yaml"
- if yaml_file.exists():
- try:
- import yaml
- with open(yaml_file, encoding="utf-8-sig") as f:
- meta = yaml.safe_load(f) or {}
- desc = meta.get("description", "")
- if desc:
- help_text = desc
- description = desc
- except Exception:
- pass
-
+ desc = _loader.read_plugin_description(plugin_dir)
handler_fn = getattr(cli_mod, f"{active_provider}_command", None) or \
getattr(cli_mod, "honcho_command", None)
results.append({
"name": active_provider,
- "help": help_text,
- "description": description,
+ "help": desc or f"Manage {active_provider} memory plugin",
+ "description": desc or "",
"setup_fn": register_cli,
"handler_fn": handler_fn,
"plugin": active_provider,
diff --git a/plugins/memory/byterover/__init__.py b/plugins/memory/byterover/__init__.py
index dd5cf3b2b88..55bc1e75f61 100644
--- a/plugins/memory/byterover/__init__.py
+++ b/plugins/memory/byterover/__init__.py
@@ -1,23 +1,14 @@
"""ByteRover memory plugin — MemoryProvider interface.
-Persistent memory via the ByteRover CLI (``brv``). Organizes knowledge into
-a hierarchical context tree with tiered retrieval (fuzzy text → LLM-driven
-search). Local-first with optional cloud sync.
+Persistent memory via the ByteRover CLI (``brv``): hierarchical context tree with
+tiered retrieval (fuzzy text → LLM-driven search), local-first with optional cloud sync.
+Original PR #3499 by hieuntg81, adapted to the MemoryProvider ABC.
-Original PR #3499 by hieuntg81, adapted to MemoryProvider ABC.
+Requires the ``brv`` CLI (npm install -g byterover-cli, or byterover.dev/install.sh).
-Requires: ``brv`` CLI installed (npm install -g byterover-cli or
-curl -fsSL https://byterover.dev/install.sh | sh).
-
-Config via environment variables (profile-scoped via each profile's .env):
- BRV_API_KEY — ByteRover API key (for cloud features, optional for local)
-
-Config via config.yaml:
- memory:
- byterover:
- auto_extract: false # disable automatic brv curate hooks
-
-Working directory: $HERMES_HOME/byterover/ (profile-scoped context tree)
+Config: BRV_API_KEY env var (cloud features; optional for local), and in config.yaml
+``memory.byterover.auto_extract: false`` to disable automatic brv curate hooks.
+Working directory: $HERMES_HOME/byterover/ (profile-scoped context tree).
"""
from __future__ import annotations
@@ -29,134 +20,88 @@ import shutil
import subprocess
import threading
from pathlib import Path
-from typing import Any, Dict, List, Optional
+from typing import Any, Callable, Dict, List, Optional
from agent.memory_provider import MemoryProvider
from tools.registry import tool_error
logger = logging.getLogger(__name__)
-# Timeouts
-_QUERY_TIMEOUT = 10 # brv query — should be fast
+_QUERY_TIMEOUT = 10 # brv query — should be fast
_CURATE_TIMEOUT = 120 # brv curate — may involve LLM processing
-
-# Minimum lengths to filter noise
-_MIN_QUERY_LEN = 10
+_MIN_QUERY_LEN = 10 # noise filters
_MIN_OUTPUT_LEN = 20
+_BOOL_WORDS = {**dict.fromkeys(("1", "true", "yes", "on"), True), **dict.fromkeys(("0", "false", "no", "off"), False)}
+
def _coerce_bool(value: Any, default: bool = False) -> bool:
- if isinstance(value, bool):
- return value
- if value is None:
- return default
- if isinstance(value, (int, float)):
+ """bool/number -> truthiness; common true/false words parsed; anything else -> default."""
+ if isinstance(value, (bool, int, float)):
return bool(value)
- if isinstance(value, str):
- text = value.strip().lower()
- if text in {"1", "true", "yes", "on"}:
- return True
- if text in {"0", "false", "no", "off"}:
- return False
- return default
+ return _BOOL_WORDS.get(value.strip().lower(), default) if isinstance(value, str) else default
def _load_plugin_config() -> Dict[str, Any]:
- """Read ByteRover's profile-scoped memory config.
-
- New memory-provider setup stores non-secret provider settings under
- ``memory.<provider>``. Some users also set ``memory.provider_config`` from
- early docs/issues, so accept it as a compatibility fallback.
- """
+ """Read ``memory.byterover``; fall back to legacy ``memory.provider_config`` (early docs used it)."""
try:
from hermes_cli.config import load_config
- config = load_config()
- memory_config = config.get("memory", {})
- if not isinstance(memory_config, dict):
- return {}
-
- provider_config = memory_config.get("byterover", {})
- if isinstance(provider_config, dict) and provider_config:
- return dict(provider_config)
-
- legacy_config = memory_config.get("provider_config", {})
- if isinstance(legacy_config, dict):
- return dict(legacy_config)
+ memory_config = load_config().get("memory", {})
+ if isinstance(memory_config, dict):
+ for key in ("byterover", "provider_config"):
+ block = memory_config.get(key, {})
+ if isinstance(block, dict) and (block or key == "provider_config"):
+ return dict(block)
except Exception:
pass
return {}
-# ---------------------------------------------------------------------------
-# brv binary resolution (cached, thread-safe)
-# ---------------------------------------------------------------------------
+# ── brv binary resolution (cached, thread-safe) ─────────────────────────────
_brv_path_lock = threading.Lock()
-_cached_brv_path: Optional[str] = None
+_cached_brv_path: Optional[str] = None # None = unresolved, "" = resolved-missing
def _resolve_brv_path() -> Optional[str]:
- """Find the brv binary on PATH or well-known install locations."""
+ """Find the brv binary on PATH or well-known install locations (resolved once; lookup is outside the lock)."""
global _cached_brv_path
with _brv_path_lock:
if _cached_brv_path is not None:
- return _cached_brv_path if _cached_brv_path != "" else None
-
- found = shutil.which("brv")
- if not found:
- home = Path.home()
- candidates = [
- home / ".brv-cli" / "bin" / "brv",
- Path("/usr/local/bin/brv"),
- home / ".npm-global" / "bin" / "brv",
- ]
- for c in candidates:
- if c.exists():
- found = str(c)
- break
-
+ return _cached_brv_path or None
+ candidates = (Path.home() / ".brv-cli/bin/brv", Path("/usr/local/bin/brv"), Path.home() / ".npm-global/bin/brv")
+ found = shutil.which("brv") or next((str(c) for c in candidates if c.exists()), None)
with _brv_path_lock:
- if _cached_brv_path is not None:
- return _cached_brv_path if _cached_brv_path != "" else None
- _cached_brv_path = found or ""
- return found
+ if _cached_brv_path is None:
+ _cached_brv_path = found or ""
+ return _cached_brv_path or None
-def _run_brv(args: List[str], timeout: int = _QUERY_TIMEOUT,
- cwd: str = None) -> dict:
+def _run_brv(args: List[str], timeout: int = _QUERY_TIMEOUT, cwd: str = None) -> dict:
"""Run a brv CLI command. Returns {success, output, error}."""
+ global _cached_brv_path
brv_path = _resolve_brv_path()
if not brv_path:
return {"success": False, "error": "brv CLI not found. Install: npm install -g byterover-cli"}
- cmd = [brv_path] + args
effective_cwd = cwd or str(_get_brv_cwd())
Path(effective_cwd).mkdir(parents=True, exist_ok=True)
-
- env = os.environ.copy()
- brv_bin_dir = str(Path(brv_path).parent)
- env["PATH"] = brv_bin_dir + os.pathsep + env.get("PATH", "")
-
+ env = {**os.environ, "PATH": str(Path(brv_path).parent) + os.pathsep + os.environ.get("PATH", "")}
try:
result = subprocess.run(
- cmd, capture_output=True, text=True, encoding='utf-8', errors='replace',
- timeout=timeout, cwd=effective_cwd, env=env,
- stdin=subprocess.DEVNULL,
+ [brv_path] + args, capture_output=True, text=True, encoding='utf-8', errors='replace',
+ timeout=timeout, cwd=effective_cwd, env=env, stdin=subprocess.DEVNULL,
)
- stdout = result.stdout.strip()
- stderr = result.stderr.strip()
-
+ stdout, stderr = result.stdout.strip(), result.stderr.strip()
if result.returncode == 0:
return {"success": True, "output": stdout}
return {"success": False, "error": stderr or stdout or f"brv exited {result.returncode}"}
-
except subprocess.TimeoutExpired:
return {"success": False, "error": f"brv timed out after {timeout}s"}
except FileNotFoundError:
- global _cached_brv_path
with _brv_path_lock:
- _cached_brv_path = None
+ _cached_brv_path = None # binary vanished; re-resolve next call
return {"success": False, "error": "brv CLI not found"}
except Exception as e:
return {"success": False, "error": str(e)}
@@ -168,54 +113,30 @@ def _get_brv_cwd() -> Path:
return get_hermes_home() / "byterover"
-# ---------------------------------------------------------------------------
-# Tool schemas
-# ---------------------------------------------------------------------------
-
-QUERY_SCHEMA = {
- "name": "brv_query",
- "description": (
- "Search ByteRover's persistent knowledge tree for relevant context. "
- "Returns memories, project knowledge, architectural decisions, and "
- "patterns from previous sessions. Use for any question where past "
- "context would help."
- ),
- "parameters": {
- "type": "object",
- "properties": {
- "query": {"type": "string", "description": "What to search for."},
- },
- "required": ["query"],
- },
-}
-
-CURATE_SCHEMA = {
- "name": "brv_curate",
- "description": (
- "Store important information in ByteRover's persistent knowledge tree. "
- "Use for architectural decisions, bug fixes, user preferences, project "
- "patterns — anything worth remembering across sessions. ByteRover's LLM "
- "automatically categorizes and organizes the memory."
- ),
- "parameters": {
- "type": "object",
- "properties": {
- "content": {"type": "string", "description": "The information to remember."},
- },
- "required": ["content"],
- },
-}
-
-STATUS_SCHEMA = {
- "name": "brv_status",
- "description": "Check ByteRover status — CLI version, context tree stats, cloud sync state.",
- "parameters": {"type": "object", "properties": {}, "required": []},
-}
-
-
-# ---------------------------------------------------------------------------
-# MemoryProvider implementation
-# ---------------------------------------------------------------------------
+# ── Tool schemas ─────────────────────────────────────────────────────────────
+
+def _schema(name: str, description: str, arg: str = "", arg_desc: str = "") -> dict:
+ props = {arg: {"type": "string", "description": arg_desc}} if arg else {}
+ return {"name": name, "description": description, "parameters": {"type": "object", "properties": props, "required": [arg] if arg else []}}
+
+
+QUERY_SCHEMA = _schema(
+ "brv_query",
+ "Search ByteRover's persistent knowledge tree for relevant context. Returns memories, project knowledge, "
+ "architectural decisions, and patterns from previous sessions. Use for any question where past context would help.",
+ "query", "What to search for.",
+)
+CURATE_SCHEMA = _schema(
+ "brv_curate",
+ "Store important information in ByteRover's persistent knowledge tree. Use for architectural decisions, bug fixes, "
+ "user preferences, project patterns — anything worth remembering across sessions. ByteRover's LLM automatically "
+ "categorizes and organizes the memory.",
+ "content", "The information to remember.",
+)
+STATUS_SCHEMA = _schema("brv_status", "Check ByteRover status — CLI version, context tree stats, cloud sync state.")
+
+
+# ── MemoryProvider implementation ────────────────────────────────────────────
class ByteRoverMemoryProvider(MemoryProvider):
"""ByteRover persistent memory via the brv CLI."""
@@ -238,19 +159,10 @@ class ByteRoverMemoryProvider(MemoryProvider):
def get_config_schema(self):
return [
- {
- "key": "api_key",
- "description": "ByteRover API key (optional, for cloud sync)",
- "secret": True,
- "env_var": "BRV_API_KEY",
- "url": "https://app.byterover.dev",
- },
- {
- "key": "auto_extract",
- "description": "Automatically curate completed turns and compression/memory hooks",
- "default": "true",
- "choices": ["true", "false"],
- },
+ {"key": "api_key", "description": "ByteRover API key (optional, for cloud sync)", "secret": True,
+ "env_var": "BRV_API_KEY", "url": "https://app.byterover.dev"},
+ {"key": "auto_extract", "description": "Automatically curate completed turns and compression/memory hooks",
+ "default": "true", "choices": ["true", "false"]},
]
def initialize(self, session_id: str, **kwargs) -> None:
@@ -269,180 +181,120 @@ class ByteRoverMemoryProvider(MemoryProvider):
"important facts, brv_status to check state."
)
- def prefetch(self, query: str, *, session_id: str = "") -> str:
- """Run brv query synchronously before the agent's first LLM call.
+ def _query(self, query: str) -> dict:
+ return _run_brv(["query", "--", query.strip()[:5000]], timeout=_QUERY_TIMEOUT, cwd=self._cwd)
+
+ def _curate(self, content: str) -> dict:
+ return _run_brv(["curate", "--", content], timeout=_CURATE_TIMEOUT, cwd=self._cwd)
+
+ def _curate_in_background(self, content: str, *, name: str, what: str, on_done: str = "") -> threading.Thread:
+ """Spawn a daemon thread that curates ``content``; failures are logged at debug, never raised."""
+ def _work():
+ try:
+ self._curate(content)
+ if on_done:
+ logger.info(on_done)
+ except Exception as e:
+ logger.debug("ByteRover %s failed: %s", what, e)
- Blocks until the query completes (up to _QUERY_TIMEOUT seconds), ensuring
- the result is available as context before the model is called.
- """
+ t = threading.Thread(target=_work, daemon=True, name=name)
+ t.start()
+ return t
+
+ def _auto_extract_enabled(self, what: str) -> bool:
+ if not self._auto_extract:
+ logger.debug("ByteRover %s skipped (auto_extract disabled)", what)
+ return self._auto_extract
+
+ def prefetch(self, query: str, *, session_id: str = "") -> str:
+ """Run brv query synchronously (blocks up to _QUERY_TIMEOUT) so context is ready before the first LLM call."""
if not query or len(query.strip()) < _MIN_QUERY_LEN:
return ""
- result = _run_brv(
- ["query", "--", query.strip()[:5000]],
- timeout=_QUERY_TIMEOUT, cwd=self._cwd,
- )
- if result["success"] and result.get("output"):
- output = result["output"].strip()
- if len(output) > _MIN_OUTPUT_LEN:
- return f"## ByteRover Context\n{output}"
- return ""
+ result = self._query(query)
+ output = (result.get("output") or "").strip() if result["success"] else ""
+ return f"## ByteRover Context\n{output}" if len(output) > _MIN_OUTPUT_LEN else ""
def queue_prefetch(self, query: str, *, session_id: str = "") -> None:
- """No-op: prefetch() now runs synchronously at turn start."""
- pass
+ """No-op: prefetch() runs synchronously at turn start."""
def sync_turn(self, user_content: str, assistant_content: str, *, session_id: str = "") -> None:
- """Curate the conversation turn in background (non-blocking)."""
+ """Curate the conversation turn in background (non-blocking); only substantive turns."""
self._turn_count += 1
- if not self._auto_extract:
- logger.debug("ByteRover sync_turn skipped (auto_extract disabled)")
- return
-
- # Only curate substantive turns
- if len(user_content.strip()) < _MIN_QUERY_LEN:
+ if not self._auto_extract_enabled("sync_turn") or len(user_content.strip()) < _MIN_QUERY_LEN:
return
-
- def _sync():
- try:
- combined = f"User: {user_content[:2000]}\nAssistant: {assistant_content[:2000]}"
- _run_brv(
- ["curate", "--", combined],
- timeout=_CURATE_TIMEOUT, cwd=self._cwd,
- )
- except Exception as e:
- logger.debug("ByteRover sync failed: %s", e)
-
- # Wait for previous sync
+ # Wait for the previous sync so curates don't pile up.
if self._sync_thread and self._sync_thread.is_alive():
self._sync_thread.join(timeout=5.0)
-
- self._sync_thread = threading.Thread(
- target=_sync, daemon=True, name="brv-sync"
- )
- self._sync_thread.start()
+ combined = f"User: {user_content[:2000]}\nAssistant: {assistant_content[:2000]}"
+ self._sync_thread = self._curate_in_background(combined, name="brv-sync", what="sync")
def on_memory_write(self, action: str, target: str, content: str) -> None:
"""Mirror built-in memory writes to ByteRover."""
- if not self._auto_extract:
- logger.debug("ByteRover memory mirror skipped (auto_extract disabled)")
- return
- if action not in {"add", "replace"} or not content:
+ if not self._auto_extract_enabled("memory mirror") or action not in {"add", "replace"} or not content:
return
-
- def _write():
- try:
- label = "User profile" if target == "user" else "Agent memory"
- _run_brv(
- ["curate", "--", f"[{label}] {content}"],
- timeout=_CURATE_TIMEOUT, cwd=self._cwd,
- )
- except Exception as e:
- logger.debug("ByteRover memory mirror failed: %s", e)
-
- t = threading.Thread(target=_write, daemon=True, name="brv-memwrite")
- t.start()
+ label = "User profile" if target == "user" else "Agent memory"
+ self._curate_in_background(f"[{label}] {content}", name="brv-memwrite", what="memory mirror")
def on_pre_compress(self, messages: List[Dict[str, Any]]) -> str:
- """Extract insights before context compression discards turns."""
- if not self._auto_extract:
- logger.debug("ByteRover pre-compression flush skipped (auto_extract disabled)")
+ """Extract insights from the last 10 user/assistant messages before compression discards them."""
+ if not self._auto_extract_enabled("pre-compression flush") or not messages:
return ""
- if not messages:
- return ""
-
- # Build a summary of messages about to be compressed
parts = []
- for msg in messages[-10:]: # last 10 messages
- role = msg.get("role", "")
- content = msg.get("content", "")
+ for msg in messages[-10:]:
+ role, content = msg.get("role", ""), msg.get("content", "")
if isinstance(content, str) and content.strip() and role in {"user", "assistant"}:
parts.append(f"{role}: {content[:500]}")
-
- if not parts:
- return ""
-
- combined = "\n".join(parts)
-
- def _flush():
- try:
- _run_brv(
- ["curate", "--", f"[Pre-compression context]\n{combined}"],
- timeout=_CURATE_TIMEOUT, cwd=self._cwd,
- )
- logger.info("ByteRover pre-compression flush: %d messages", len(parts))
- except Exception as e:
- logger.debug("ByteRover pre-compression flush failed: %s", e)
-
- t = threading.Thread(target=_flush, daemon=True, name="brv-flush")
- t.start()
+ if parts:
+ self._curate_in_background(
+ "[Pre-compression context]\n" + "\n".join(parts), name="brv-flush", what="pre-compression flush",
+ on_done=f"ByteRover pre-compression flush: {len(parts)} messages",
+ )
return ""
def get_tool_schemas(self) -> List[Dict[str, Any]]:
return [QUERY_SCHEMA, CURATE_SCHEMA, STATUS_SCHEMA]
def handle_tool_call(self, tool_name: str, args: dict, **kwargs) -> str:
- if tool_name == "brv_query":
- return self._tool_query(args)
- elif tool_name == "brv_curate":
- return self._tool_curate(args)
- elif tool_name == "brv_status":
- return self._tool_status()
- return tool_error(f"Unknown tool: {tool_name}")
+ handler = self._TOOLS.get(tool_name)
+ if handler is None:
+ return tool_error(f"Unknown tool: {tool_name}")
+ return handler(self, args)
def shutdown(self) -> None:
if self._sync_thread and self._sync_thread.is_alive():
self._sync_thread.join(timeout=10.0)
- # -- Tool implementations ------------------------------------------------
+ # Tool implementations
+
+ @staticmethod
+ def _tool_result(result: dict, fail_msg: str, on_ok: Callable[[str], dict]) -> str:
+ if not result["success"]:
+ return tool_error(result.get("error", fail_msg))
+ return json.dumps(on_ok(result.get("output", "")))
def _tool_query(self, args: dict) -> str:
query = args.get("query", "")
if not query:
return tool_error("query is required")
- result = _run_brv(
- ["query", "--", query.strip()[:5000]],
- timeout=_QUERY_TIMEOUT, cwd=self._cwd,
- )
-
- if not result["success"]:
- return tool_error(result.get("error", "Query failed"))
-
- output = result.get("output", "").strip()
- if not output or len(output) < _MIN_OUTPUT_LEN:
- return json.dumps({"result": "No relevant memories found."})
-
- # Truncate very long results
- if len(output) > 8000:
- output = output[:8000] + "\n\n[... truncated]"
-
- return json.dumps({"result": output})
+ def fmt(output: str) -> dict:
+ output = output.strip()
+ if len(output) < _MIN_OUTPUT_LEN:
+ return {"result": "No relevant memories found."}
+ return {"result": output[:8000] + "\n\n[... truncated]" if len(output) > 8000 else output}
+ return self._tool_result(self._query(query), "Query failed", fmt)
def _tool_curate(self, args: dict) -> str:
content = args.get("content", "")
if not content:
return tool_error("content is required")
+ return self._tool_result(self._curate(content), "Curate failed", lambda _: {"result": "Memory curated successfully."})
- result = _run_brv(
- ["curate", "--", content],
- timeout=_CURATE_TIMEOUT, cwd=self._cwd,
- )
-
- if not result["success"]:
- return tool_error(result.get("error", "Curate failed"))
-
- return json.dumps({"result": "Memory curated successfully."})
-
- def _tool_status(self) -> str:
- result = _run_brv(["status"], timeout=15, cwd=self._cwd)
- if not result["success"]:
- return tool_error(result.get("error", "Status check failed"))
- return json.dumps({"status": result.get("output", "")})
+ def _tool_status(self, args: dict) -> str:
+ return self._tool_result(_run_brv(["status"], timeout=15, cwd=self._cwd), "Status check failed", lambda out: {"status": out})
+ _TOOLS = {"brv_query": _tool_query, "brv_curate": _tool_curate, "brv_status": _tool_status}
-# ---------------------------------------------------------------------------
-# Plugin entry point
-# ---------------------------------------------------------------------------
def register(ctx) -> None:
"""Register ByteRover as a memory provider plugin."""
diff --git a/plugins/memory/config_schema.py b/plugins/memory/config_schema.py
index 2a9560b1ece..1af9844eff3 100644
--- a/plugins/memory/config_schema.py
+++ b/plugins/memory/config_schema.py
@@ -1,22 +1,15 @@
"""Declarative configuration schema for memory provider plugins.
-Each memory provider plugin *declares* its configurable surface in a
-``config_schema.py`` next to its ``__init__.py`` — the fields, their types,
-which values are secrets, and (for selects) the allowed options. A single
-generic renderer in the desktop UI and a single generic ``GET/PUT
-/api/memory/providers/{name}/config`` endpoint pair drive the whole
-experience, so adding a provider config surface is pure declaration with no
-bespoke UI components.
-
-Schema files are loaded by path (like the provider plugins themselves), never
-via package import: plugin ``__init__.py`` files pull in the agent runtime,
-which must not load into the web server. A ``config_schema.py`` may only
-import from this module.
-
-This module is intentionally pure data: it imports nothing from the
-config/env layer. ``web_server`` owns the generic read/write logic that
-interprets these declarations, dispatching on ``ProviderConfigSchema.storage``
-to the matching backend.
+Each provider *declares* its configurable surface in a ``config_schema.py`` next
+to its ``__init__.py`` (fields, kinds, secrets, select options); one generic
+renderer in the desktop UI and one generic ``GET/PUT
+/api/memory/providers/{name}/config`` endpoint pair drive the whole experience.
+
+Schema files are loaded by path, never via package import: plugin ``__init__.py``
+files pull in the agent runtime, which must not load into the web server. A
+``config_schema.py`` may only import from this module, and this module is pure
+data (nothing from the config/env layer). ``web_server`` owns the read/write
+logic, dispatching on ``ProviderConfigSchema.storage``.
"""
from __future__ import annotations
@@ -53,17 +46,12 @@ class ProviderFieldOption:
class ProviderField:
"""One configurable field on a memory provider.
- A field is stored in exactly one place, decided by ``kind``:
-
- * non-secret kinds — persisted to the provider's config via its storage
- backend under ``key``.
- * ``secret`` — persisted to the env store under ``env_key`` and never read
- back out over the API (only an ``is_set`` flag is surfaced).
-
- ``aliases`` and ``env_fallbacks`` let a field read legacy values written by
- earlier CLI/env setup without re-introducing per-provider code. ``inline``
- marks the curated subset shown in the compact panel; the rest surface only
- in the full-config modal. ``group`` buckets fields within that modal.
+ Stored in exactly one place by ``kind``: non-secret kinds go to the provider's
+ storage backend under ``key``; ``secret`` goes to the env store under
+ ``env_key`` and is never read back over the API (only an ``is_set`` flag).
+ ``aliases``/``env_fallbacks`` read legacy values from earlier CLI/env setup.
+ ``inline`` marks the compact-panel subset; the rest appear only in the
+ full-config modal, bucketed by ``group``.
"""
key: str
@@ -110,14 +98,11 @@ _SCHEMA_CACHE: dict[str, ProviderConfigSchema] = {}
def get_provider_config_schema(name: str) -> ProviderConfigSchema | None:
- """Return the ``CONFIG_SCHEMA`` declared by the provider plugin ``name``.
+ """``CONFIG_SCHEMA`` declared by provider ``name``; None (no panel) without a ``config_schema.py``.
- Providers without a ``config_schema.py`` (e.g. ``builtin``) return ``None``
- and simply render no config panel. The cache keys on the resolved schema
- file, not the name: user-installed plugins are per-profile, so one
- profile's lookup must never answer for another's.
+ The cache keys on the resolved schema file, not the name: user-installed
+ plugins are per-profile, so one profile's lookup must never answer for another's.
"""
-
from plugins.memory import find_provider_dir
provider_dir = find_provider_dir(name)
diff --git a/plugins/memory/holographic/__init__.py b/plugins/memory/holographic/__init__.py
index 2e5f86a8cf5..08f799005fb 100644
--- a/plugins/memory/holographic/__init__.py
+++ b/plugins/memory/holographic/__init__.py
@@ -20,6 +20,7 @@ from __future__ import annotations
import json
import logging
import re
+from pathlib import Path
from typing import Any, Dict, List
from agent.memory_provider import MemoryProvider
@@ -32,10 +33,6 @@ from hermes_cli.config import cfg_get
logger = logging.getLogger(__name__)
-# ---------------------------------------------------------------------------
-# Tool schemas (unchanged from original PR)
-# ---------------------------------------------------------------------------
-
FACT_STORE_SCHEMA = {
"name": "fact_store",
"description": (
@@ -90,15 +87,21 @@ FACT_FEEDBACK_SCHEMA = {
},
}
+# Auto-extraction patterns (on_session_end): user preferences -> user_pref, decisions -> project.
+_PREF_PATTERNS = [
+ re.compile(r'\bI\s+(?:prefer|like|love|use|want|need)\s+(.+)', re.IGNORECASE),
+ re.compile(r'\bmy\s+(?:favorite|preferred|default)\s+\w+\s+is\s+(.+)', re.IGNORECASE),
+ re.compile(r'\bI\s+(?:always|never|usually)\s+(.+)', re.IGNORECASE),
+]
+_DECISION_PATTERNS = [
+ re.compile(r'\bwe\s+(?:decided|agreed|chose)\s+(?:to\s+)?(.+)', re.IGNORECASE),
+ re.compile(r'\bthe\s+project\s+(?:uses|needs|requires)\s+(.+)', re.IGNORECASE),
+]
-# ---------------------------------------------------------------------------
-# Config
-# ---------------------------------------------------------------------------
def _load_plugin_config() -> dict:
try:
- # Canonical loader: behavioral read now honors the managed-scope
- # overlay + ${VAR} expansion (e.g. an api key template) too.
+ # Canonical loader: honors the managed-scope overlay + ${VAR} expansion.
from hermes_cli.config import load_config_readonly
all_config = load_config_readonly()
return cfg_get(all_config, "plugins", "hermes-memory-store", default={}) or {}
@@ -106,9 +109,9 @@ def _load_plugin_config() -> dict:
return {}
-# ---------------------------------------------------------------------------
-# MemoryProvider implementation
-# ---------------------------------------------------------------------------
+def _results(results: list) -> str:
+ return json.dumps({"results": results, "count": len(results)})
+
class HolographicMemoryProvider(MemoryProvider):
"""Holographic memory with structured facts, entity resolution, and HRR retrieval."""
@@ -128,16 +131,14 @@ class HolographicMemoryProvider(MemoryProvider):
def save_config(self, values, hermes_home):
"""Write config to config.yaml under plugins.hermes-memory-store."""
- from pathlib import Path
config_path = Path(hermes_home) / "config.yaml"
try:
import yaml
- # Write-back round-trip: raw read is correct (merged defaults
- # must not be persisted back into the user's file).
+ # Raw read for the write-back round-trip: merged defaults must not
+ # be persisted into the user's file.
from hermes_cli.config import read_user_config_raw
existing = read_user_config_raw(config_path)
- existing.setdefault("plugins", {})
- existing["plugins"]["hermes-memory-store"] = values
+ existing.setdefault("plugins", {})["hermes-memory-store"] = values
with open(config_path, "w", encoding="utf-8") as f:
yaml.dump(existing, f, default_flow_style=False)
except Exception:
@@ -156,24 +157,19 @@ class HolographicMemoryProvider(MemoryProvider):
def initialize(self, session_id: str, **kwargs) -> None:
from hermes_constants import get_hermes_home
_hermes_home = str(get_hermes_home())
- _default_db = _hermes_home + "/memory_store.db"
- db_path = self._config.get("db_path", _default_db)
- # Expand $HERMES_HOME in user-supplied paths so config values like
- # "$HERMES_HOME/memory_store.db" or "~/.hermes/memory_store.db" both
- # resolve to the active profile's directory.
+ db_path = self._config.get("db_path", _hermes_home + "/memory_store.db")
+ # Expand $HERMES_HOME so configured paths resolve to the active profile's directory.
if isinstance(db_path, str):
- db_path = db_path.replace("$HERMES_HOME", _hermes_home)
- db_path = db_path.replace("${HERMES_HOME}", _hermes_home)
- default_trust = float(self._config.get("default_trust", 0.5))
+ db_path = db_path.replace("$HERMES_HOME", _hermes_home).replace("${HERMES_HOME}", _hermes_home)
hrr_dim = int(self._config.get("hrr_dim", 1024))
- hrr_weight = float(self._config.get("hrr_weight", 0.3))
- temporal_decay = int(self._config.get("temporal_decay_half_life", 0))
- self._store = MemoryStore(db_path=db_path, default_trust=default_trust, hrr_dim=hrr_dim)
+ self._store = MemoryStore(
+ db_path=db_path, default_trust=float(self._config.get("default_trust", 0.5)), hrr_dim=hrr_dim,
+ )
self._retriever = FactRetriever(
store=self._store,
- temporal_decay_half_life=temporal_decay,
- hrr_weight=hrr_weight,
+ temporal_decay_half_life=int(self._config.get("temporal_decay_half_life", 0)),
+ hrr_weight=float(self._config.get("hrr_weight", 0.3)),
hrr_dim=hrr_dim,
)
self._session_id = session_id
@@ -182,9 +178,7 @@ class HolographicMemoryProvider(MemoryProvider):
if not self._store:
return ""
try:
- total = self._store._conn.execute(
- "SELECT COUNT(*) FROM facts"
- ).fetchone()[0]
+ total = self._store._conn.execute("SELECT COUNT(*) FROM facts").fetchone()[0]
except Exception:
total = 0
if total == 0:
@@ -208,39 +202,35 @@ class HolographicMemoryProvider(MemoryProvider):
results = self._retriever.search(query, min_trust=self._min_trust, limit=5)
if not results:
return ""
- lines = []
- for r in results:
- trust = r.get("trust_score", r.get("trust", 0))
- lines.append(f"- [{trust:.1f}] {r.get('content', '')}")
+ lines = [f"- [{r.get('trust_score', r.get('trust', 0)):.1f}] {r.get('content', '')}" for r in results]
return "## Holographic Memory\n" + "\n".join(lines)
except Exception as e:
logger.debug("Holographic prefetch failed: %s", e)
return ""
def sync_turn(self, user_content: str, assistant_content: str, *, session_id: str = "") -> None:
- # Holographic memory stores explicit facts via tools, not auto-sync.
- # The on_session_end hook handles auto-extraction if configured.
+ # Facts are stored explicitly via tools; on_session_end handles auto-extraction if configured.
pass
def get_tool_schemas(self) -> List[Dict[str, Any]]:
return [FACT_STORE_SCHEMA, FACT_FEEDBACK_SCHEMA]
def handle_tool_call(self, tool_name: str, args: Dict[str, Any], **kwargs) -> str:
- if tool_name == "fact_store":
- return self._handle_fact_store(args)
- elif tool_name == "fact_feedback":
- return self._handle_fact_feedback(args)
- return tool_error(f"Unknown tool: {tool_name}")
+ handler = self._TOOL_HANDLERS.get(tool_name)
+ if handler is None:
+ return tool_error(f"Unknown tool: {tool_name}")
+ try:
+ return handler(self, args)
+ except KeyError as exc:
+ return tool_error(f"Missing required argument: {exc}")
+ except Exception as exc:
+ return tool_error(str(exc))
def on_session_end(self, messages: List[Dict[str, Any]]) -> None:
# is_truthy_value: the config schema declares auto_extract as a string
- # enum ("false"/"true"), and a plain truthiness check treats the string
- # "false" as enabled (#57682).
- if not is_truthy_value(self._config.get("auto_extract", False)):
- return
- if not self._store or not messages:
- return
- self._auto_extract_facts(messages)
+ # enum ("false"/"true"); plain truthiness would treat "false" as enabled.
+ if is_truthy_value(self._config.get("auto_extract", False)) and self._store and messages:
+ self._auto_extract_facts(messages)
def on_memory_write(self, action: str, target: str, content: str) -> None:
"""Mirror built-in memory writes as facts."""
@@ -252,12 +242,9 @@ class HolographicMemoryProvider(MemoryProvider):
logger.debug("Holographic memory_write mirror failed: %s", e)
def shutdown(self) -> None:
- # Release the shared SQLite connection deterministically on the
- # caller's thread. Dropping the reference alone leaves fd finalization
- # to GC, which keeps the connection (and its write lock) alive on a
- # long-running gateway and prolongs the "database is locked" contention
- # this store's shared-connection refcounting is meant to eliminate.
- # close() is idempotent and refcount-guarded, so siblings stay safe.
+ # Release the shared SQLite connection on the caller's thread: leaving
+ # it to GC keeps the connection (and its write lock) alive on a
+ # long-running gateway. close() is idempotent and refcount-guarded.
if self._store is not None:
try:
self._store.close()
@@ -267,196 +254,116 @@ class HolographicMemoryProvider(MemoryProvider):
self._retriever = None
# -- Tool handlers -------------------------------------------------------
+ # KeyError from args[...] / Exception are turned into tool_error by handle_tool_call.
def _handle_fact_store(self, args: dict) -> str:
- try:
- action = args["action"]
- store = self._store
- retriever = self._retriever
-
- if action == "add":
- fact_id = store.add_fact(
- args["content"],
- category=args.get("category", "general"),
- tags=args.get("tags", ""),
- )
- return json.dumps({"fact_id": fact_id, "status": "added"})
-
- elif action == "search":
- results = retriever.search(
- args["query"],
- category=args.get("category"),
- min_trust=float(args.get("min_trust", self._min_trust)),
- limit=int(args.get("limit", 10)),
- )
- return json.dumps({"results": results, "count": len(results)})
-
- elif action == "probe":
- results = retriever.probe(
- args["entity"],
- category=args.get("category"),
- limit=int(args.get("limit", 10)),
- )
- return json.dumps({"results": results, "count": len(results)})
-
- elif action == "related":
- results = retriever.related(
- args["entity"],
- category=args.get("category"),
- limit=int(args.get("limit", 10)),
- )
- return json.dumps({"results": results, "count": len(results)})
-
- elif action == "reason":
- entities = args.get("entities", [])
- if not entities:
- return tool_error("reason requires 'entities' list")
- results = retriever.reason(
- entities,
- category=args.get("category"),
- limit=int(args.get("limit", 10)),
- )
- return json.dumps({"results": results, "count": len(results)})
-
- elif action == "contradict":
- results = retriever.contradict(
- category=args.get("category"),
- limit=int(args.get("limit", 10)),
- )
- return json.dumps({"results": results, "count": len(results)})
-
- elif action == "update":
- updated = store.update_fact(
- int(args["fact_id"]),
- content=args.get("content"),
- trust_delta=float(args["trust_delta"]) if "trust_delta" in args else None,
- tags=args.get("tags"),
- category=args.get("category"),
- )
- return json.dumps({"updated": updated})
-
- elif action == "remove":
- removed = store.remove_fact(int(args["fact_id"]))
- return json.dumps({"removed": removed})
-
- elif action == "list":
- facts = store.list_facts(
- category=args.get("category"),
- min_trust=float(args.get("min_trust", 0.0)),
- limit=int(args.get("limit", 10)),
- )
- return json.dumps({"facts": facts, "count": len(facts)})
-
- else:
- return tool_error(f"Unknown action: {action}")
+ action = args["action"]
+ handler = self._FACT_STORE_ACTIONS.get(action)
+ if handler is None:
+ return tool_error(f"Unknown action: {action}")
+ return handler(self, args)
+
+ def _act_add(self, args: dict) -> str:
+ fact_id = self._store.add_fact(args["content"], category=args.get("category", "general"), tags=args.get("tags", ""))
+ return json.dumps({"fact_id": fact_id, "status": "added"})
+
+ def _act_search(self, args: dict) -> str:
+ return _results(self._retriever.search(
+ args["query"], category=args.get("category"),
+ min_trust=float(args.get("min_trust", self._min_trust)), limit=int(args.get("limit", 10)),
+ ))
+
+ def _act_entity(self, args: dict, method: str) -> str:
+ """Shared body of 'probe' and 'related' (single-entity retriever queries)."""
+ return _results(getattr(self._retriever, method)(
+ args["entity"], category=args.get("category"), limit=int(args.get("limit", 10)),
+ ))
+
+ def _act_reason(self, args: dict) -> str:
+ entities = args.get("entities", [])
+ if not entities:
+ return tool_error("reason requires 'entities' list")
+ return _results(self._retriever.reason(entities, category=args.get("category"), limit=int(args.get("limit", 10))))
+
+ def _act_contradict(self, args: dict) -> str:
+ return _results(self._retriever.contradict(category=args.get("category"), limit=int(args.get("limit", 10))))
+
+ def _act_update(self, args: dict) -> str:
+ updated = self._store.update_fact(
+ int(args["fact_id"]), content=args.get("content"),
+ trust_delta=float(args["trust_delta"]) if "trust_delta" in args else None,
+ tags=args.get("tags"), category=args.get("category"),
+ )
+ return json.dumps({"updated": updated})
- except KeyError as exc:
- return tool_error(f"Missing required argument: {exc}")
- except Exception as exc:
- return tool_error(str(exc))
+ def _act_remove(self, args: dict) -> str:
+ return json.dumps({"removed": self._store.remove_fact(int(args["fact_id"]))})
+
+ def _act_list(self, args: dict) -> str:
+ facts = self._store.list_facts(
+ category=args.get("category"), min_trust=float(args.get("min_trust", 0.0)), limit=int(args.get("limit", 10)),
+ )
+ return json.dumps({"facts": facts, "count": len(facts)})
def _handle_fact_feedback(self, args: dict) -> str:
- try:
- fact_id = int(args["fact_id"])
- helpful = args["action"] == "helpful"
- result = self._store.record_feedback(fact_id, helpful=helpful)
- return json.dumps(result)
- except KeyError as exc:
- return tool_error(f"Missing required argument: {exc}")
- except Exception as exc:
- return tool_error(str(exc))
+ return json.dumps(self._store.record_feedback(int(args["fact_id"]), helpful=args["action"] == "helpful"))
+
+ _FACT_STORE_ACTIONS = {
+ "add": _act_add, "search": _act_search,
+ "probe": lambda self, args: self._act_entity(args, "probe"),
+ "related": lambda self, args: self._act_entity(args, "related"),
+ "reason": _act_reason, "contradict": _act_contradict,
+ "update": _act_update, "remove": _act_remove, "list": _act_list,
+ }
+ _TOOL_HANDLERS = {"fact_store": _handle_fact_store, "fact_feedback": _handle_fact_feedback}
# -- Auto-extraction (on_session_end) ------------------------------------
def _auto_extract_facts(self, messages: list) -> None:
- # Local import (pattern used in initialize()): the compressor module is
- # heavier than this plugin and is only needed when auto_extract is on.
+ # Local import: the compressor module is heavier than this plugin and
+ # only needed when auto_extract is on.
from agent.context_compressor import (
_MERGED_PRIOR_CONTEXT_HEADER,
_MERGED_SUMMARY_DELIMITER,
is_compaction_summary_message,
)
- def _pre_delimiter_user_segment(msg: dict):
- """Return the genuine user text preceding a merged-into-tail
- compaction summary, or None when the whole message is a summary.
-
- Merge-into-tail messages (agent/context_compressor.py ~3163-3190)
- wrap real prior tail content BEFORE ``_MERGED_SUMMARY_DELIMITER``,
- prefixed with ``_MERGED_PRIOR_CONTEXT_HEADER``, then append the
- generated handoff summary AFTER the delimiter. Dropping the whole
- row (as ``is_compaction_summary_message`` alone would suggest)
- discards that genuine pre-delimiter content too (#57690 review).
- Only the summary suffix must be excluded from harvesting.
- """
- content = msg.get("content", "")
- if not isinstance(content, str) or _MERGED_SUMMARY_DELIMITER not in content:
- return None
- pre = content.split(_MERGED_SUMMARY_DELIMITER, 1)[0]
- if pre.startswith(_MERGED_PRIOR_CONTEXT_HEADER):
- pre = pre[len(_MERGED_PRIOR_CONTEXT_HEADER):]
- pre = pre.strip()
- return pre or None
-
- _PREF_PATTERNS = [
- re.compile(r'\bI\s+(?:prefer|like|love|use|want|need)\s+(.+)', re.IGNORECASE),
- re.compile(r'\bmy\s+(?:favorite|preferred|default)\s+\w+\s+is\s+(.+)', re.IGNORECASE),
- re.compile(r'\bI\s+(?:always|never|usually)\s+(.+)', re.IGNORECASE),
- ]
- _DECISION_PATTERNS = [
- re.compile(r'\bwe\s+(?:decided|agreed|chose)\s+(?:to\s+)?(.+)', re.IGNORECASE),
- re.compile(r'\bthe\s+project\s+(?:uses|needs|requires)\s+(.+)', re.IGNORECASE),
- ]
-
extracted = 0
for msg in messages:
if msg.get("role") != "user":
continue
- # Compaction handoff summaries can be inserted as role="user"
- # messages; their prose reliably matches the decision patterns, so
- # without this guard the compactor's own output is stored as a
- # durable "fact" on every rollover (#57682). A merge-into-tail
- # summary also carries genuine pre-delimiter user content in the
- # SAME row; harvest that segment instead of dropping the whole
- # message (#57690 review).
- pre_delimiter_segment = _pre_delimiter_user_segment(msg)
- if pre_delimiter_segment is not None:
- content = pre_delimiter_segment
+ content = msg.get("content", "")
+ # Compaction handoff summaries arrive as role="user" and reliably
+ # match the decision patterns; skip them so the compactor's own
+ # output is never stored as a durable fact. A merge-into-tail row
+ # holds genuine prior user text BEFORE _MERGED_SUMMARY_DELIMITER
+ # (prefixed with the header) and the summary AFTER it — harvest
+ # only the pre-delimiter segment.
+ if isinstance(content, str) and _MERGED_SUMMARY_DELIMITER in content:
+ pre = content.split(_MERGED_SUMMARY_DELIMITER, 1)[0]
+ if pre.startswith(_MERGED_PRIOR_CONTEXT_HEADER):
+ pre = pre[len(_MERGED_PRIOR_CONTEXT_HEADER):]
+ if pre.strip():
+ content = pre.strip()
+ elif is_compaction_summary_message(msg):
+ continue
elif is_compaction_summary_message(msg):
continue
- else:
- content = msg.get("content", "")
if not isinstance(content, str) or len(content) < 10:
continue
- for pattern in _PREF_PATTERNS:
- if pattern.search(content):
- try:
- self._store.add_fact(content[:400], category="user_pref")
- extracted += 1
- except Exception:
- pass
- break
-
- for pattern in _DECISION_PATTERNS:
- if pattern.search(content):
+ for patterns, category in ((_PREF_PATTERNS, "user_pref"), (_DECISION_PATTERNS, "project")):
+ if any(p.search(content) for p in patterns):
try:
- self._store.add_fact(content[:400], category="project")
+ self._store.add_fact(content[:400], category=category)
extracted += 1
except Exception:
pass
- break
if extracted:
logger.info("Auto-extracted %d facts from conversation", extracted)
-# ---------------------------------------------------------------------------
-# Plugin entry point
-# ---------------------------------------------------------------------------
-
def register(ctx) -> None:
"""Register the holographic memory provider with the plugin system."""
- config = _load_plugin_config()
- provider = HolographicMemoryProvider(config=config)
- ctx.register_memory_provider(provider)
+ ctx.register_memory_provider(HolographicMemoryProvider(config=_load_plugin_config()))
diff --git a/plugins/memory/holographic/holographic.py b/plugins/memory/holographic/holographic.py
index 31c94e10f51..c6acf0fbef5 100644
--- a/plugins/memory/holographic/holographic.py
+++ b/plugins/memory/holographic/holographic.py
@@ -1,22 +1,15 @@
"""Holographic Reduced Representations (HRR) with phase encoding.
-HRRs are a vector symbolic architecture for encoding compositional structure
-into fixed-width distributed representations. This module uses *phase vectors*:
-each concept is a vector of angles in [0, 2π). The algebraic operations are:
-
- bind — circular convolution (phase addition) — associates two concepts
+Each concept is a vector of angles in [0, 2π). Operations:
+ bind — circular convolution (phase addition) — associates two concepts
unbind — circular correlation (phase subtraction) — retrieves a bound value
- bundle — superposition (circular mean) — merges multiple concepts
-
-Phase encoding is numerically stable, avoids the magnitude collapse of
-traditional complex-number HRRs, and maps cleanly to cosine similarity.
+ bundle — superposition (circular mean) — merges multiple concepts
-Atoms are generated deterministically from SHA-256 so representations are
-identical across processes, machines, and language versions.
+Phase encoding avoids the magnitude collapse of complex-number HRRs and maps
+cleanly to cosine similarity. Atoms derive deterministically from SHA-256 so
+representations are identical across processes, machines, and Python versions.
-References:
- Plate (1995) — Holographic Reduced Representations
- Gayler (2004) — Vector Symbolic Architectures answer Jackendoff's challenges
+References: Plate (1995) HRRs; Gayler (2004) Vector Symbolic Architectures.
"""
import hashlib
@@ -28,6 +21,7 @@ try:
import numpy as np
_HAS_NUMPY = True
except ImportError:
+ np = None # type: ignore[assignment]
_HAS_NUMPY = False
logger = logging.getLogger(__name__)
@@ -41,250 +35,131 @@ def _require_numpy() -> None:
raise RuntimeError("numpy is required for holographic operations")
-def _np():
- """Return the numpy module after the runtime availability guard."""
- _require_numpy()
- return np # type: ignore[name-defined]
-
-
def encode_atom(word: str, dim: int = 1024) -> "np.ndarray":
- """Deterministic phase vector via SHA-256 counter blocks.
-
- Uses hashlib (not numpy RNG) for cross-platform reproducibility.
+ """Deterministic phase vector: SHA-256 counter blocks of f"{word}:{i}" -> uint16 -> [0, 2π).
- Algorithm:
- - Generate enough SHA-256 blocks by hashing f"{word}:{i}" for i=0,1,2,...
- - Concatenate digests, interpret as uint16 values via struct.unpack
- - Scale to [0, 2π): phases = values * (2π / 65536)
- - Truncate to dim elements
- - Returns np.float64 array of shape (dim,)
+ hashlib rather than numpy RNG so atoms are reproducible across platforms.
"""
_require_numpy()
-
- # Each SHA-256 digest is 32 bytes = 16 uint16 values.
- values_per_block = 16
- blocks_needed = math.ceil(dim / values_per_block)
-
uint16_values: list[int] = []
- for i in range(blocks_needed):
+ for i in range(math.ceil(dim / 16)): # 32-byte digest = 16 uint16 values
digest = hashlib.sha256(f"{word}:{i}".encode()).digest()
uint16_values.extend(struct.unpack("<16H", digest))
-
- phases = np.array(uint16_values[:dim], dtype=np.float64) * (_TWO_PI / 65536.0)
- return phases
+ return np.array(uint16_values[:dim], dtype=np.float64) * (_TWO_PI / 65536.0)
def bind(a: "np.ndarray", b: "np.ndarray") -> "np.ndarray":
- """Circular convolution = element-wise phase addition.
-
- Binding associates two concepts into a single composite vector.
- The result is dissimilar to both inputs (quasi-orthogonal).
- """
+ """Circular convolution = phase addition; result is quasi-orthogonal to both inputs."""
_require_numpy()
return (a + b) % _TWO_PI
def unbind(memory: "np.ndarray", key: "np.ndarray") -> "np.ndarray":
- """Circular correlation = element-wise phase subtraction.
-
- Unbinding retrieves the value associated with a key from a memory vector.
- unbind(bind(a, b), a) ≈ b (up to superposition noise)
- """
+ """Circular correlation = phase subtraction; unbind(bind(a, b), a) ≈ b."""
_require_numpy()
return (memory - key) % _TWO_PI
def bundle(*vectors: "np.ndarray") -> "np.ndarray":
- """Superposition via circular mean of complex exponentials.
-
- Bundling merges multiple vectors into one that is similar to each input.
- The result can hold O(sqrt(dim)) items before similarity degrades.
- """
+ """Superposition via circular mean; holds O(sqrt(dim)) items before similarity degrades."""
_require_numpy()
complex_sum = np.sum([np.exp(1j * v) for v in vectors], axis=0)
return np.angle(complex_sum) % _TWO_PI
def similarity(a: "np.ndarray", b: "np.ndarray") -> float:
- """Phase cosine similarity. Range [-1, 1].
-
- Returns 1.0 for identical vectors, near 0.0 for random (unrelated) vectors,
- and -1.0 for perfectly anti-correlated vectors.
- """
+ """Phase cosine similarity in [-1, 1]; ~0 for unrelated vectors."""
_require_numpy()
return float(np.mean(np.cos(a - b)))
def encode_text(text: str, dim: int = 1024) -> "np.ndarray":
- """Bag-of-words: bundle of atom vectors for each token.
-
- Tokenizes by lowercasing, splitting on whitespace, and stripping
- leading/trailing punctuation from each token.
-
- Returns bundle of all token atom vectors.
- If text is empty or produces no tokens, returns encode_atom("__hrr_empty__", dim).
- """
+ """Bag-of-words bundle of token atoms; empty text -> encode_atom("__hrr_empty__")."""
_require_numpy()
-
- tokens = [
- token.strip(".,!?;:\"'()[]{}")
- for token in text.lower().split()
- ]
- tokens = [t for t in tokens if t]
-
+ tokens = [t for t in (tok.strip(".,!?;:\"'()[]{}") for tok in text.lower().split()) if t]
if not tokens:
return encode_atom("__hrr_empty__", dim)
-
- atom_vectors = [encode_atom(token, dim) for token in tokens]
- return bundle(*atom_vectors)
+ return bundle(*[encode_atom(token, dim) for token in tokens])
def encode_fact(content: str, entities: list[str], dim: int = 1024) -> "np.ndarray":
- """Structured encoding: content bound to ROLE_CONTENT, each entity bound to ROLE_ENTITY, all bundled.
-
- Role vectors are reserved atoms: "__hrr_role_content__", "__hrr_role_entity__"
-
- Components:
- 1. bind(encode_text(content, dim), encode_atom("__hrr_role_content__", dim))
- 2. For each entity: bind(encode_atom(entity.lower(), dim), encode_atom("__hrr_role_entity__", dim))
- 3. bundle all components together
-
- This enables algebraic extraction:
- unbind(fact, bind(entity, ROLE_ENTITY)) ≈ content_vector
- """
+ """bundle(bind(text, ROLE_CONTENT), bind(entity_i, ROLE_ENTITY)...), so
+ unbind(fact, bind(entity, ROLE_ENTITY)) ≈ content_vector."""
_require_numpy()
-
role_content = encode_atom("__hrr_role_content__", dim)
role_entity = encode_atom("__hrr_role_entity__", dim)
-
- components: list[np.ndarray] = [
- bind(encode_text(content, dim), role_content)
- ]
-
+ components = [bind(encode_text(content, dim), role_content)]
for entity in entities:
components.append(bind(encode_atom(entity.lower(), dim), role_entity))
-
return bundle(*components)
def phases_to_bytes(phases: "np.ndarray", dim: int | None = None) -> bytes:
- """Serialize phase vectors as float32 blobs.
-
- float32 halves SQLite BLOB storage versus the legacy float64 format
- (4 KB + a 4-byte format prefix instead of 8 KB at dim=1024) while
- preserving enough precision for phase-similarity retrieval.
- ``bytes_to_phases`` keeps reading legacy float64 blobs for backward
- compatibility.
-
- When ``dim`` is 1 the prefixed float32 blob (8 bytes) collides in size
- with a raw float64 blob (8 bytes), making the format ambiguous. In
- that case we fall back to writing raw float64 so that ``bytes_to_phases``
- can never misinterpret the blob.
+ """Serialize as prefixed float32 (half the size of legacy float64 blobs).
+
+ At dim=1 the prefixed float32 blob and a raw float64 blob are both 8 bytes,
+ so we write legacy float64 there to keep ``bytes_to_phases`` unambiguous.
"""
- numpy = _np()
+ _require_numpy()
if dim is None:
dim = int(phases.shape[0])
- float32_blob_bytes = len(_FLOAT32_BLOB_PREFIX) + dim * numpy.dtype(numpy.float32).itemsize
- float64_bytes = dim * numpy.dtype(numpy.float64).itemsize
- if float32_blob_bytes == float64_bytes:
- # dim=1: sizes collide, write legacy float64 to stay unambiguous
- return numpy.asarray(phases, dtype=numpy.float64).tobytes()
- payload = numpy.asarray(phases, dtype=numpy.float32).tobytes()
- return _FLOAT32_BLOB_PREFIX + payload
+ if len(_FLOAT32_BLOB_PREFIX) + dim * np.dtype(np.float32).itemsize == dim * np.dtype(np.float64).itemsize:
+ return np.asarray(phases, dtype=np.float64).tobytes()
+ return _FLOAT32_BLOB_PREFIX + np.asarray(phases, dtype=np.float32).tobytes()
def bytes_to_phases(data: bytes, dim: int | None = None) -> "np.ndarray":
- """Deserialize a phase vector from new float32 or legacy float64 storage.
-
- New float32 blobs carry a small prefix so callers can round-trip without
- knowing ``dim``. Legacy float64 blobs are raw NumPy bytes and remain
- readable for backward compatibility. The returned array is copied and
- promoted to float64 so downstream HRR math keeps the existing numerical
- behavior.
-
- When ``dim`` is 1 the prefixed float32 blob and the raw float64 blob are
- both 8 bytes, so size alone cannot disambiguate. ``phases_to_bytes``
- avoids writing prefixed blobs in that case; here we guard the remaining
- collision window (a legacy float64 blob that happens to start with the
- ``HRR1`` prefix) by preferring the legacy interpretation when sizes
- match and the caller supplied ``dim``.
+ """Deserialize prefixed float32 or legacy raw float64 blobs (always returns float64).
+
+ With ``dim`` given, a prefixed blob whose size equals the float64 size
+ (dim=1) is read as legacy float64: ``phases_to_bytes`` never writes a
+ prefixed blob at that size, so such a blob must be legacy data.
"""
- numpy = _np()
-
- if dim is not None:
- float32_payload_bytes = dim * numpy.dtype(numpy.float32).itemsize
- float32_blob_bytes = len(_FLOAT32_BLOB_PREFIX) + float32_payload_bytes
- float64_bytes = dim * numpy.dtype(numpy.float64).itemsize
-
- # When sizes collide (dim=1), prefer legacy float64 for a blob that
- # starts with the prefix, because phases_to_bytes never writes a
- # prefixed float32 blob at dim=1 — any such blob must be legacy.
- if float32_blob_bytes == float64_bytes:
- if len(data) == float64_bytes:
- return numpy.frombuffer(data, dtype=numpy.float64).copy()
- if data.startswith(_FLOAT32_BLOB_PREFIX):
- payload_len = len(data) - len(_FLOAT32_BLOB_PREFIX)
- raise ValueError(
- f"HRR vector blob has {len(data)} bytes ({payload_len} payload bytes after "
- f"the float32 prefix); expected {float64_bytes} (legacy float64) for dim={dim}"
- )
- raise ValueError(
- f"HRR legacy vector blob has {len(data)} bytes; expected "
- f"{float64_bytes} (float64) for dim={dim}"
- )
-
- if data.startswith(_FLOAT32_BLOB_PREFIX) and len(data) == float32_blob_bytes:
- payload = data[len(_FLOAT32_BLOB_PREFIX):]
- return numpy.frombuffer(payload, dtype=numpy.float32).astype(numpy.float64)
- if len(data) == float64_bytes:
- return numpy.frombuffer(data, dtype=numpy.float64).copy()
- if data.startswith(_FLOAT32_BLOB_PREFIX):
- payload_len = len(data) - len(_FLOAT32_BLOB_PREFIX)
- raise ValueError(
- f"HRR vector blob has {len(data)} bytes ({payload_len} payload bytes after "
- f"the float32 prefix); expected {float32_blob_bytes} (prefixed float32) "
- f"or {float64_bytes} (legacy float64) for dim={dim}"
- )
+ _require_numpy()
+ f32, f64 = np.dtype(np.float32).itemsize, np.dtype(np.float64).itemsize
+ plen = len(_FLOAT32_BLOB_PREFIX)
+ prefixed = data.startswith(_FLOAT32_BLOB_PREFIX)
+
+ if dim is None:
+ if prefixed:
+ payload = data[plen:]
+ if len(payload) % f32 != 0:
+ raise ValueError(f"HRR float32 vector blob has invalid payload byte length: {len(payload)}")
+ return np.frombuffer(payload, dtype=np.float32).astype(np.float64)
+ if len(data) % f64 != 0:
+ raise ValueError(f"HRR legacy vector blob has invalid byte length: {len(data)}")
+ return np.frombuffer(data, dtype=np.float64).copy()
+
+ float32_blob_bytes = plen + dim * f32
+ float64_bytes = dim * f64
+ collides = float32_blob_bytes == float64_bytes
+ if not collides and prefixed and len(data) == float32_blob_bytes:
+ return np.frombuffer(data[plen:], dtype=np.float32).astype(np.float64)
+ if len(data) == float64_bytes:
+ return np.frombuffer(data, dtype=np.float64).copy()
+ if prefixed:
+ expected = (f"{float64_bytes} (legacy float64)" if collides
+ else f"{float32_blob_bytes} (prefixed float32) or {float64_bytes} (legacy float64)")
raise ValueError(
- f"HRR legacy vector blob has {len(data)} bytes; expected "
- f"{float64_bytes} (float64) for dim={dim}"
+ f"HRR vector blob has {len(data)} bytes ({len(data) - plen} payload bytes after "
+ f"the float32 prefix); expected {expected} for dim={dim}"
)
-
- if data.startswith(_FLOAT32_BLOB_PREFIX):
- payload = data[len(_FLOAT32_BLOB_PREFIX):]
- if len(payload) % numpy.dtype(numpy.float32).itemsize != 0:
- raise ValueError(
- f"HRR float32 vector blob has invalid payload byte length: {len(payload)}"
- )
- return numpy.frombuffer(payload, dtype=numpy.float32).astype(numpy.float64)
-
- if len(data) % numpy.dtype(numpy.float64).itemsize != 0:
- raise ValueError(f"HRR legacy vector blob has invalid byte length: {len(data)}")
- return numpy.frombuffer(data, dtype=numpy.float64).copy()
+ raise ValueError(
+ f"HRR legacy vector blob has {len(data)} bytes; expected "
+ f"{float64_bytes} (float64) for dim={dim}"
+ )
def snr_estimate(dim: int, n_items: int) -> float:
- """Signal-to-noise ratio estimate for holographic storage.
-
- SNR = sqrt(dim / n_items) when n_items > 0, else inf.
-
- The SNR falls below 2.0 when n_items > dim / 4, meaning retrieval
- errors become likely. Logs a warning when this threshold is crossed.
- """
+ """SNR = sqrt(dim / n_items) (inf when empty); warns below 2.0 (n_items > dim/4)."""
_require_numpy()
-
if n_items <= 0:
return float("inf")
-
snr = math.sqrt(dim / n_items)
-
if snr < 2.0:
logger.warning(
"HRR storage near capacity: SNR=%.2f (dim=%d, n_items=%d). "
"Retrieval accuracy may degrade. Consider increasing dim or reducing stored items.",
- snr,
- dim,
- n_items,
+ snr, dim, n_items,
)
-
return snr
diff --git a/plugins/memory/holographic/retrieval.py b/plugins/memory/holographic/retrieval.py
index 2bbcb71f473..a8a3fa86f12 100644
--- a/plugins/memory/holographic/retrieval.py
+++ b/plugins/memory/holographic/retrieval.py
@@ -7,6 +7,7 @@ Jaccard similarity reranking and trust-weighted scoring.
from __future__ import annotations
import math
+from collections.abc import Callable
from datetime import datetime, timezone
from typing import TYPE_CHECKING
@@ -18,6 +19,11 @@ try:
except ImportError:
import holographic as hrr # type: ignore[no-redef]
+_FACT_COLUMNS = (
+ "fact_id, content, category, tags, trust_score, "
+ "retrieval_count, helpful_count, created_at, updated_at"
+)
+
class FactRetriever:
"""Multi-strategy fact retrieval with trust-weighted scoring."""
@@ -26,9 +32,7 @@ class FactRetriever:
self,
store: MemoryStore,
temporal_decay_half_life: int = 0, # days, 0 = disabled
- fts_weight: float = 0.4,
- jaccard_weight: float = 0.3,
- hrr_weight: float = 0.3,
+ fts_weight: float = 0.4, jaccard_weight: float = 0.3, hrr_weight: float = 0.3,
hrr_dim: int = 1024,
):
self.store = store
@@ -37,415 +41,184 @@ class FactRetriever:
# Auto-redistribute weights if numpy unavailable
if hrr_weight > 0 and not hrr._HAS_NUMPY:
- fts_weight = 0.6
- jaccard_weight = 0.4
- hrr_weight = 0.0
+ fts_weight, jaccard_weight, hrr_weight = 0.6, 0.4, 0.0
+ self.fts_weight, self.jaccard_weight, self.hrr_weight = fts_weight, jaccard_weight, hrr_weight
- self.fts_weight = fts_weight
- self.jaccard_weight = jaccard_weight
- self.hrr_weight = hrr_weight
+ def search(self, query: str, category: str | None = None, min_trust: float = 0.3, limit: int = 10) -> list[dict]:
+ """Hybrid search: FTS5 candidates (limit*3) → Jaccard + HRR rerank → trust
+ weighting → optional temporal decay 0.5^(age_days / half_life).
- def search(
- self,
- query: str,
- category: str | None = None,
- min_trust: float = 0.3,
- limit: int = 10,
- ) -> list[dict]:
- """Hybrid search: FTS5 candidates → Jaccard rerank → trust weighting.
-
- Pipeline:
- 1. FTS5 search: Get limit*3 candidates from SQLite full-text search
- 2. Jaccard boost: Token overlap between query and fact content
- 3. Trust weighting: final_score = relevance * trust_score
- 4. Temporal decay (optional): decay = 0.5^(age_days / half_life)
-
- Returns list of dicts with fact data + 'score' field, sorted by score desc.
+ Returns fact dicts with a 'score' field, sorted by score desc.
"""
- # Stage 1: Get FTS5 candidates (more than limit for reranking headroom)
candidates = self._fts_candidates(query, category, min_trust, limit * 3)
-
if not candidates:
return []
- # Stage 2: Rerank with Jaccard + trust + optional decay
query_tokens = self._tokenize(query)
- # The query vector is loop-invariant — encode it at most once, on
- # the first candidate that actually carries an HRR vector. Lazy on
- # purpose: migrated stores can have FTS candidates whose hrr_vector
- # was never backfilled (MemoryStore._init_db adds the column
- # without backfilling), and those must not pay for an encode
- # nothing will use. encode_text is deterministic (SHA-256 counter
- # blocks), so the hoisted vector is bit-identical to what the
- # per-candidate calls produced.
+ # Query vector is loop-invariant; encode lazily on the first candidate
+ # that carries an HRR vector so migrated stores whose hrr_vector was
+ # never backfilled don't pay for an encode nothing uses.
query_vec = None
- scored = []
-
for fact in candidates:
- content_tokens = self._tokenize(fact["content"])
- tag_tokens = self._tokenize(fact.get("tags", ""))
- all_tokens = content_tokens | tag_tokens
-
+ all_tokens = self._tokenize(fact["content"]) | self._tokenize(fact.get("tags", ""))
jaccard = self._jaccard_similarity(query_tokens, all_tokens)
- fts_score = fact.get("fts_rank", 0.0)
-
- # HRR similarity
+ hrr_sim = 0.5 # neutral
if self.hrr_weight > 0 and fact.get("hrr_vector"):
fact_vec = hrr.bytes_to_phases(fact["hrr_vector"], dim=self.hrr_dim)
if query_vec is None:
query_vec = hrr.encode_text(query, self.hrr_dim)
hrr_sim = (hrr.similarity(query_vec, fact_vec) + 1.0) / 2.0 # shift to [0,1]
- else:
- hrr_sim = 0.5 # neutral
-
- # Combine FTS5 + Jaccard + HRR
- relevance = (self.fts_weight * fts_score
- + self.jaccard_weight * jaccard
- + self.hrr_weight * hrr_sim)
-
- # Trust weighting
- score = relevance * fact["trust_score"]
-
- # Optional temporal decay
+ relevance = (self.fts_weight * fact.get("fts_rank", 0.0)
+ + self.jaccard_weight * jaccard
+ + self.hrr_weight * hrr_sim)
+ fact["score"] = relevance * fact["trust_score"]
if self.half_life > 0:
- score *= self._temporal_decay(fact.get("updated_at") or fact.get("created_at"))
-
- fact["score"] = score
- scored.append(fact)
+ fact["score"] *= self._temporal_decay(fact.get("updated_at") or fact.get("created_at"))
- # Sort by score descending, return top limit
- scored.sort(key=lambda x: x["score"], reverse=True)
- results = scored[:limit]
- # Strip raw HRR bytes — callers expect JSON-serializable dicts
+ candidates.sort(key=lambda x: x["score"], reverse=True)
+ results = candidates[:limit]
for fact in results:
- fact.pop("hrr_vector", None)
+ fact.pop("hrr_vector", None) # callers expect JSON-serializable dicts
return results
- def probe(
- self,
- entity: str,
- category: str | None = None,
- limit: int = 10,
- ) -> list[dict]:
- """Compositional entity query using HRR algebra.
-
- Unbinds entity from memory bank to extract associated content.
- This is NOT keyword search — it uses algebraic structure to find facts
- where the entity plays a structural role.
-
- Falls back to FTS5 search if numpy unavailable.
+ def probe(self, entity: str, category: str | None = None, limit: int = 10) -> list[dict]:
+ """Compositional entity query: unbind bind(entity, ROLE_ENTITY) from the
+ category bank (or each fact vector) to find facts where the entity plays
+ a structural role. Not keyword search. Falls back to FTS5 without numpy.
"""
if not hrr._HAS_NUMPY:
- # Fallback to keyword search on entity name
return self.search(entity, category=category, limit=limit)
- conn = self.store._conn
-
- # Encode entity as role-bound vector
role_entity = hrr.encode_atom("__hrr_role_entity__", self.hrr_dim)
entity_vec = hrr.encode_atom(entity.lower(), self.hrr_dim)
probe_key = hrr.bind(entity_vec, role_entity)
- # Try category-specific bank first, then all facts
+ # Try the category-specific bank first, then individual fact vectors
if category:
- bank_name = f"cat:{category}"
- bank_row = conn.execute(
+ bank_row = self.store._conn.execute(
"SELECT vector FROM memory_banks WHERE bank_name = ?",
- (bank_name,),
+ (f"cat:{category}",),
).fetchone()
if bank_row:
- bank_vec = hrr.bytes_to_phases(bank_row["vector"], dim=self.hrr_dim)
- extracted = hrr.unbind(bank_vec, probe_key)
- # Use extracted signal to score individual facts
- return self._score_facts_by_vector(
- extracted, category=category, limit=limit
+ extracted = hrr.unbind(hrr.bytes_to_phases(bank_row["vector"], dim=self.hrr_dim), probe_key)
+ return self._rank_by_vector(
+ self._vector_rows(category), lambda _f, fact_vec: hrr.similarity(extracted, fact_vec), limit,
)
- # Score against individual fact vectors directly
- where = "WHERE hrr_vector IS NOT NULL"
- params: list = []
- if category:
- where += " AND category = ?"
- params.append(category)
-
- rows = conn.execute(
- f"""
- SELECT fact_id, content, category, tags, trust_score,
- retrieval_count, helpful_count, created_at, updated_at,
- hrr_vector
- FROM facts
- {where}
- """,
- params,
- ).fetchall()
-
+ rows = self._vector_rows(category)
if not rows:
- # Final fallback: keyword search
return self.search(entity, category=category, limit=limit)
- # role_content is loop-invariant — encode it once (deterministic
- # SHA-256-based atom) instead of once per fact row.
+ # role_content is loop-invariant — encode once, not per row.
role_content = hrr.encode_atom("__hrr_role_content__", self.hrr_dim)
- scored = []
- for row in rows:
- fact = dict(row)
- fact_vec = hrr.bytes_to_phases(fact.pop("hrr_vector"), dim=self.hrr_dim)
- # Unbind probe key from fact to see if entity is structurally present
+
+ def _sim(fact: dict, fact_vec) -> float:
+ # Does unbinding the probe key leave the fact's content signal?
residual = hrr.unbind(fact_vec, probe_key)
- # Compare residual against content signal
content_vec = hrr.bind(hrr.encode_text(fact["content"], self.hrr_dim), role_content)
- sim = hrr.similarity(residual, content_vec)
- fact["score"] = (sim + 1.0) / 2.0 * fact["trust_score"]
- scored.append(fact)
-
- scored.sort(key=lambda x: x["score"], reverse=True)
- return scored[:limit]
-
- def related(
- self,
- entity: str,
- category: str | None = None,
- limit: int = 10,
- ) -> list[dict]:
- """Discover facts that share structural connections with an entity.
+ return hrr.similarity(residual, content_vec)
- Unlike probe (which finds facts *about* an entity), related finds
- facts that are connected through shared context — e.g., other entities
- mentioned alongside this one, or content that overlaps structurally.
+ return self._rank_by_vector(rows, _sim, limit)
- Falls back to FTS5 search if numpy unavailable.
+ def related(self, entity: str, category: str | None = None, limit: int = 10) -> list[dict]:
+ """Facts structurally connected to an entity (shared context), not just
+ facts *about* it as in probe. Falls back to FTS5 without numpy.
"""
if not hrr._HAS_NUMPY:
return self.search(entity, category=category, limit=limit)
- conn = self.store._conn
-
- # Encode entity as a bare atom (not role-bound — we want ANY structural match)
+ # Bare atom, not role-bound — we want ANY structural match
entity_vec = hrr.encode_atom(entity.lower(), self.hrr_dim)
- # Get all facts with vectors
- where = "WHERE hrr_vector IS NOT NULL"
- params: list = []
- if category:
- where += " AND category = ?"
- params.append(category)
-
- rows = conn.execute(
- f"""
- SELECT fact_id, content, category, tags, trust_score,
- retrieval_count, helpful_count, created_at, updated_at,
- hrr_vector
- FROM facts
- {where}
- """,
- params,
- ).fetchall()
-
+ rows = self._vector_rows(category)
if not rows:
return self.search(entity, category=category, limit=limit)
- # Score each fact by how much the entity's atom appears in its vector
- # This catches both role-bound entity matches AND content word matches
- # Both role atoms are loop-invariant — encode them once here
- # (deterministic SHA-256-based atoms) instead of twice per fact row.
+ # Both role atoms are loop-invariant — encode once, not per row.
role_entity = hrr.encode_atom("__hrr_role_entity__", self.hrr_dim)
role_content = hrr.encode_atom("__hrr_role_content__", self.hrr_dim)
- scored = []
- for row in rows:
- fact = dict(row)
- fact_vec = hrr.bytes_to_phases(fact.pop("hrr_vector"), dim=self.hrr_dim)
- # Check structural similarity: unbind entity from fact
+ def _sim(fact: dict, fact_vec) -> float:
+ # A residual similar to ANY role vector means the entity plays a
+ # structural role in the fact; take the max over both roles.
residual = hrr.unbind(fact_vec, entity_vec)
- # A high-similarity residual to ANY known role vector means this entity
- # plays a structural role in the fact
+ return max(hrr.similarity(residual, role_entity), hrr.similarity(residual, role_content))
- entity_role_sim = hrr.similarity(residual, role_entity)
- content_role_sim = hrr.similarity(residual, role_content)
- # Take the max — entity could appear in either role
- best_sim = max(entity_role_sim, content_role_sim)
+ return self._rank_by_vector(rows, _sim, limit)
- fact["score"] = (best_sim + 1.0) / 2.0 * fact["trust_score"]
- scored.append(fact)
-
- scored.sort(key=lambda x: x["score"], reverse=True)
- return scored[:limit]
-
- def reason(
- self,
- entities: list[str],
- category: str | None = None,
- limit: int = 10,
- ) -> list[dict]:
- """Multi-entity compositional query — vector-space JOIN.
-
- Given multiple entities, algebraically intersects their structural
- connections to find facts related to ALL of them simultaneously.
- This is compositional reasoning that no embedding DB can do.
-
- Example: reason(["peppi", "backend"]) finds facts where peppi AND
- backend both play structural roles — without keyword matching.
-
- Falls back to FTS5 search if numpy unavailable.
+ def reason(self, entities: list[str], category: str | None = None, limit: int = 10) -> list[dict]:
+ """Multi-entity compositional query (vector-space JOIN): facts where ALL
+ entities play structural roles. Falls back to FTS5 without numpy.
"""
if not hrr._HAS_NUMPY or not entities:
- # Fallback: search with all entities as keywords
- query = " ".join(entities)
- return self.search(query, category=category, limit=limit)
+ return self.search(" ".join(entities), category=category, limit=limit)
- conn = self.store._conn
role_entity = hrr.encode_atom("__hrr_role_entity__", self.hrr_dim)
+ probe_keys = [
+ hrr.bind(hrr.encode_atom(entity.lower(), self.hrr_dim), role_entity)
+ for entity in entities
+ ]
- # For each entity, compute what the bank "remembers" about it
- # by unbinding entity+role from each fact vector
- entity_residuals = []
- for entity in entities:
- entity_vec = hrr.encode_atom(entity.lower(), self.hrr_dim)
- probe_key = hrr.bind(entity_vec, role_entity)
- entity_residuals.append(probe_key)
-
- # Get all facts with vectors
- where = "WHERE hrr_vector IS NOT NULL"
- params: list = []
- if category:
- where += " AND category = ?"
- params.append(category)
-
- rows = conn.execute(
- f"""
- SELECT fact_id, content, category, tags, trust_score,
- retrieval_count, helpful_count, created_at, updated_at,
- hrr_vector
- FROM facts
- {where}
- """,
- params,
- ).fetchall()
-
+ rows = self._vector_rows(category)
if not rows:
- query = " ".join(entities)
- return self.search(query, category=category, limit=limit)
+ return self.search(" ".join(entities), category=category, limit=limit)
- # Score each fact by how much EACH entity is structurally present.
- # A fact scores high only if ALL entities have structural presence
- # (AND semantics via min, vs OR which would use mean/max).
role_content = hrr.encode_atom("__hrr_role_content__", self.hrr_dim)
- scored = []
- for row in rows:
- fact = dict(row)
- fact_vec = hrr.bytes_to_phases(fact.pop("hrr_vector"), dim=self.hrr_dim)
-
- entity_scores = []
- for probe_key in entity_residuals:
- residual = hrr.unbind(fact_vec, probe_key)
- sim = hrr.similarity(residual, role_content)
- entity_scores.append(sim)
-
- min_sim = min(entity_scores)
- fact["score"] = (min_sim + 1.0) / 2.0 * fact["trust_score"]
- scored.append(fact)
+ def _sim(fact: dict, fact_vec) -> float:
+ # AND semantics via min: high only if EVERY entity is structurally present.
+ return min(
+ hrr.similarity(hrr.unbind(fact_vec, key), role_content) for key in probe_keys
+ )
- scored.sort(key=lambda x: x["score"], reverse=True)
- return scored[:limit]
+ return self._rank_by_vector(rows, _sim, limit)
- def contradict(
- self,
- category: str | None = None,
- threshold: float = 0.3,
- limit: int = 10,
- ) -> list[dict]:
- """Find potentially contradictory facts via entity overlap + content divergence.
-
- Two facts contradict when they share entities (same subject) but have
- low content-vector similarity (different claims). This is automated
- memory hygiene — no other memory system does this.
-
- Returns pairs of facts with a contradiction score.
- Falls back to empty list if numpy unavailable.
+ def contradict(self, category: str | None = None, threshold: float = 0.3, limit: int = 10) -> list[dict]:
+ """Memory hygiene: pairs of facts that share entities (same subject) but
+ have low content-vector similarity (different claims). Empty without numpy.
"""
if not hrr._HAS_NUMPY:
return []
- conn = self.store._conn
-
- # Get all facts with vectors and their linked entities
- where = "WHERE f.hrr_vector IS NOT NULL"
- params: list = []
- if category:
- where += " AND f.category = ?"
- params.append(category)
-
- rows = conn.execute(
- f"""
- SELECT f.fact_id, f.content, f.category, f.tags, f.trust_score,
- f.created_at, f.updated_at, f.hrr_vector
- FROM facts f
- {where}
- """,
- params,
- ).fetchall()
-
+ rows = self._vector_rows(
+ category,
+ columns="fact_id, content, category, tags, trust_score, created_at, updated_at, hrr_vector",
+ )
if len(rows) < 2:
return []
+ # O(n²) guard: ~125K comparisons at 500 facts is acceptable; above that
+ # only compare the most recently updated facts.
+ if len(rows) > 500:
+ rows = sorted(rows, key=lambda r: r["updated_at"] or r["created_at"], reverse=True)[:500]
- # Guard against O(n²) explosion on large fact stores.
- # At 500 facts, that's ~125K comparisons — acceptable.
- # Above that, only check the most recently updated facts.
- _MAX_CONTRADICT_FACTS = 500
- if len(rows) > _MAX_CONTRADICT_FACTS:
- rows = sorted(rows, key=lambda r: r["updated_at"] or r["created_at"], reverse=True)
- rows = rows[:_MAX_CONTRADICT_FACTS]
-
- # Build entity sets per fact
- fact_entities: dict[int, set[str]] = {}
- for row in rows:
- fid = row["fact_id"]
- entity_rows = conn.execute(
- """
- SELECT e.name FROM entities e
- JOIN fact_entities fe ON fe.entity_id = e.entity_id
- WHERE fe.fact_id = ?
- """,
- (fid,),
- ).fetchall()
- fact_entities[fid] = {r["name"].lower() for r in entity_rows}
-
- # Compare all pairs: high entity overlap + low content similarity = contradiction
facts = [dict(r) for r in rows]
- contradictions = []
+ for fact in facts:
+ entity_rows = self.store._conn.execute(
+ "SELECT e.name FROM entities e JOIN fact_entities fe ON fe.entity_id = e.entity_id WHERE fe.fact_id = ?",
+ (fact["fact_id"],),
+ ).fetchall()
+ fact["_entities"] = {r["name"].lower() for r in entity_rows}
+ fact["_vec"] = hrr.bytes_to_phases(fact.pop("hrr_vector"), dim=self.hrr_dim)
- for i in range(len(facts)):
- for j in range(i + 1, len(facts)):
- f1, f2 = facts[i], facts[j]
- ents1 = fact_entities.get(f1["fact_id"], set())
- ents2 = fact_entities.get(f2["fact_id"], set())
+ def _public(fact: dict) -> dict:
+ return {k: v for k, v in fact.items() if k not in ("_entities", "_vec")}
+ contradictions = []
+ for i, f1 in enumerate(facts):
+ for f2 in facts[i + 1:]:
+ ents1, ents2 = f1["_entities"], f2["_entities"]
if not ents1 or not ents2:
continue
-
- # Entity overlap (Jaccard)
- entity_overlap = len(ents1 & ents2) / len(ents1 | ents2) if (ents1 | ents2) else 0.0
-
+ entity_overlap = len(ents1 & ents2) / len(ents1 | ents2)
if entity_overlap < 0.3:
- continue # Not enough entity overlap to be contradictory
-
- # Content similarity via HRR vectors
- v1 = hrr.bytes_to_phases(f1["hrr_vector"], dim=self.hrr_dim)
- v2 = hrr.bytes_to_phases(f2["hrr_vector"], dim=self.hrr_dim)
- content_sim = hrr.similarity(v1, v2)
-
- # High entity overlap + low content similarity = potential contradiction
- # contradiction_score: higher = more contradictory
+ continue # not enough shared subject to be contradictory
+ content_sim = hrr.similarity(f1["_vec"], f2["_vec"])
+ # High entity overlap + low content similarity = contradiction
contradiction_score = entity_overlap * (1.0 - (content_sim + 1.0) / 2.0)
-
if contradiction_score >= threshold:
- # Strip hrr_vector from output (not JSON serializable)
- f1_clean = {k: v for k, v in f1.items() if k != "hrr_vector"}
- f2_clean = {k: v for k, v in f2.items() if k != "hrr_vector"}
contradictions.append({
- "fact_a": f1_clean,
- "fact_b": f2_clean,
+ "fact_a": _public(f1),
+ "fact_b": _public(f2),
"entity_overlap": round(entity_overlap, 3),
"content_similarity": round(content_sim, 3),
"contradiction_score": round(contradiction_score, 3),
@@ -455,214 +228,109 @@ class FactRetriever:
contradictions.sort(key=lambda x: x["contradiction_score"], reverse=True)
return contradictions[:limit]
- def _score_facts_by_vector(
- self,
- target_vec: "np.ndarray",
- category: str | None = None,
- limit: int = 10,
- ) -> list[dict]:
- """Score facts by similarity to a target vector."""
- conn = self.store._conn
+ # -- Vector scoring helpers -----------------------------------------------
+ def _vector_rows(self, category: str | None, columns: str = _FACT_COLUMNS + ", hrr_vector") -> list:
+ """All facts that carry an HRR vector, optionally filtered by category."""
where = "WHERE hrr_vector IS NOT NULL"
params: list = []
if category:
where += " AND category = ?"
params.append(category)
+ return self.store._conn.execute(f"SELECT {columns} FROM facts {where}", params).fetchall()
- rows = conn.execute(
- f"""
- SELECT fact_id, content, category, tags, trust_score,
- retrieval_count, helpful_count, created_at, updated_at,
- hrr_vector
- FROM facts
- {where}
- """,
- params,
- ).fetchall()
-
+ def _rank_by_vector(self, rows: list, sim_fn: Callable[[dict, object], float], limit: int) -> list[dict]:
+ """Score each row as (sim + 1) / 2 * trust_score (sim shifted to [0, 1]), sorted desc."""
scored = []
for row in rows:
fact = dict(row)
fact_vec = hrr.bytes_to_phases(fact.pop("hrr_vector"), dim=self.hrr_dim)
- sim = hrr.similarity(target_vec, fact_vec)
- fact["score"] = (sim + 1.0) / 2.0 * fact["trust_score"]
+ fact["score"] = (sim_fn(fact, fact_vec) + 1.0) / 2.0 * fact["trust_score"]
scored.append(fact)
-
scored.sort(key=lambda x: x["score"], reverse=True)
return scored[:limit]
- def _fts_candidates(
- self,
- query: str,
- category: str | None,
- min_trust: float,
- limit: int,
- ) -> list[dict]:
- """Get raw FTS5 candidates from the store.
-
- Uses the store's database connection directly for FTS5 MATCH
- with rank scoring. Normalizes FTS5 rank to [0, 1] range.
- """
- conn = self.store._conn
-
- # Build query - FTS5 rank is negative (lower = better match)
- # We need to join facts_fts with facts to get all columns
- params: list = []
- where_clauses = ["facts_fts MATCH ?"]
- # FTS5 defaults to AND-between-tokens, which kills recall on
- # natural-language queries ("what happened with the deployment
- # rollback"). Sanitize: drop stopwords, OR-join content tokens, so
- # any significant term can match.
- params.append(self._sanitize_fts_query(query))
-
- if category:
- where_clauses.append("f.category = ?")
- params.append(category)
-
- where_clauses.append("f.trust_score >= ?")
- params.append(min_trust)
-
- where_sql = " AND ".join(where_clauses)
-
- sql = f"""
- SELECT f.*, facts_fts.rank as fts_rank_raw
- FROM facts_fts
- JOIN facts f ON f.fact_id = facts_fts.rowid
- WHERE {where_sql}
- ORDER BY facts_fts.rank
- LIMIT ?
- """
- params.append(limit)
-
+ # -- FTS / lexical helpers ------------------------------------------------
+
+ def _fts_candidates(self, query: str, category: str | None, min_trust: float, limit: int) -> list[dict]:
+ """Raw FTS5 MATCH candidates with rank normalized to [0, 1] as 'fts_rank'."""
+ category_clause = "AND f.category = ? " if category else ""
+ params = [self._sanitize_fts_query(query)] + ([category] if category else []) + [min_trust, limit]
+ sql = (
+ "SELECT f.*, facts_fts.rank as fts_rank_raw FROM facts_fts "
+ "JOIN facts f ON f.fact_id = facts_fts.rowid "
+ f"WHERE facts_fts MATCH ? {category_clause}AND f.trust_score >= ? "
+ "ORDER BY facts_fts.rank LIMIT ?"
+ )
try:
- rows = conn.execute(sql, params).fetchall()
+ rows = self.store._conn.execute(sql, params).fetchall()
except Exception:
- # FTS5 MATCH can fail on malformed queries — fall back to empty
- return []
-
+ return [] # FTS5 MATCH can fail on malformed queries
if not rows:
return []
- # Normalize FTS5 rank: rank is negative, lower = better
- # Convert to positive score in [0, 1] range
- raw_ranks = [abs(row["fts_rank_raw"]) for row in rows]
- max_rank = max(raw_ranks) if raw_ranks else 1.0
- max_rank = max(max_rank, 1e-6) # avoid div by zero
-
- results = []
- for row, raw_rank in zip(rows, raw_ranks):
- fact = dict(row)
- fact.pop("fts_rank_raw", None)
- fact["fts_rank"] = raw_rank / max_rank # normalize to [0, 1]
- results.append(fact)
-
+ results = [dict(row) for row in rows]
+ # FTS5 rank is negative (lower = better); normalize |rank| / max to [0, 1]
+ max_rank = max(max(abs(f["fts_rank_raw"]) for f in results), 1e-6) # avoid div by zero
+ for fact in results:
+ fact["fts_rank"] = abs(fact.pop("fts_rank_raw")) / max_rank
return results
@staticmethod
def _tokenize(text: str) -> set[str]:
- """Simple whitespace tokenization with lowercasing.
-
- Strips common punctuation. No stemming/lemmatization (Phase 1).
- """
+ """Lowercase whitespace tokens with surrounding punctuation stripped (no stemming)."""
if not text:
return set()
- # Split on whitespace, lowercase, strip punctuation
- tokens = set()
- for word in text.lower().split():
- cleaned = word.strip(".,;:!?\"'()[]{}#@<>")
- if cleaned:
- tokens.add(cleaned)
- return tokens
-
- # Stopwords dropped before FTS5 OR-expansion. Short English function
- # words that carry no retrieval signal and force false-negative AND
- # matches when left in the query.
- _FTS_STOPWORDS = frozenset({
- "a", "about", "above", "after", "again", "all", "am", "an", "and",
- "any", "are", "as", "at", "be", "because", "been", "before", "being",
- "between", "both", "but", "by", "can", "could", "did", "do", "does",
- "doing", "don", "down", "during", "each", "few", "for", "from",
- "further", "had", "has", "have", "having", "he", "her", "here",
- "hers", "herself", "him", "himself", "his", "how", "i", "if", "in",
- "into", "is", "it", "its", "itself", "just", "me", "more", "most",
- "my", "myself", "no", "nor", "not", "now", "of", "off", "on", "once",
- "only", "or", "other", "our", "ours", "ourselves", "out", "over",
- "own", "same", "she", "should", "so", "some", "such", "than", "that",
- "the", "their", "theirs", "them", "themselves", "then", "there",
- "these", "they", "this", "those", "through", "to", "too", "under",
- "until", "up", "very", "was", "we", "were", "what", "when", "where",
- "which", "while", "who", "whom", "why", "will", "with", "would",
- "you", "your", "yours", "yourself", "yourselves",
- })
+ return {c for c in (w.strip(".,;:!?\"'()[]{}#@<>") for w in text.lower().split()) if c}
+
+ # Stopwords dropped before FTS5 OR-expansion: short English function words
+ # that carry no retrieval signal and force false-negative AND matches.
+ _FTS_STOPWORDS = frozenset("""
+ a about above after again all am an and any are as at be because been before being
+ between both but by can could did do does doing don down during each few for from
+ further had has have having he her here hers herself him himself his how i if in
+ into is it its itself just me more most my myself no nor not now of off on once
+ only or other our ours ourselves out over own same she should so some such than that
+ the their theirs them themselves then there these they this those through to too under
+ until up very was we were what when where which while who whom why will with would
+ you your yours yourself yourselves
+ """.split())
@classmethod
def _sanitize_fts_query(cls, query: str) -> str:
- """Convert a natural-language query to an FTS5-safe OR expression.
-
- FTS5 treats a multi-word MATCH argument as AND-joined by default,
- which tanks recall on prose queries. This helper:
- - tokenizes the query
- - drops stopwords and short (<2 char) tokens
- - strips FTS5 special characters from each token
- - OR-joins the survivors
+ """Natural-language query -> FTS5-safe OR expression of quoted tokens.
- If nothing remains (pathological query), falls back to the raw
- query so the caller sees zero results instead of a SQL error.
+ FTS5 AND-joins a multi-word MATCH by default, which tanks recall on prose.
+ Drops stopwords and <2-char tokens, strips FTS5 operator chars, and
+ phrase-quotes each survivor. If nothing survives, returns the raw query
+ (caller gets zero results rather than a SQL error).
"""
if not query:
return ""
- # Strip FTS5 operator characters from EACH token to avoid
- # accidentally creating a malformed query.
- _FTS_SPECIAL = '"()*^:-+'
- tokens: list[str] = []
- for raw in query.lower().split():
- cleaned = raw.strip(".,;:!?\"'()[]{}#@<>") .translate(
- str.maketrans("", "", _FTS_SPECIAL)
- )
- if len(cleaned) < 2:
- continue
- if cleaned in cls._FTS_STOPWORDS:
- continue
- # FTS5 phrase-literal each token to ensure no special chars
- # sneak through as operators.
- tokens.append(f'"{cleaned}"')
- if not tokens:
- # Fallback: raw query (likely returns 0, but never crashes)
- return query
- return " OR ".join(tokens)
+ strip_special = str.maketrans("", "", '"()*^:-+')
+ tokens = [
+ f'"{cleaned}"'
+ for cleaned in (raw.strip(".,;:!?\"'()[]{}#@<>").translate(strip_special) for raw in query.lower().split())
+ if len(cleaned) >= 2 and cleaned not in cls._FTS_STOPWORDS
+ ]
+ return " OR ".join(tokens) if tokens else query
@staticmethod
def _jaccard_similarity(set_a: set, set_b: set) -> float:
"""Jaccard similarity coefficient: |A ∩ B| / |A ∪ B|."""
- if not set_a or not set_b:
- return 0.0
- intersection = len(set_a & set_b)
- union = len(set_a | set_b)
- return intersection / union if union > 0 else 0.0
+ return len(set_a & set_b) / len(set_a | set_b) if set_a and set_b else 0.0
def _temporal_decay(self, timestamp_str: str | None) -> float:
- """Exponential decay: 0.5^(age_days / half_life_days).
-
- Returns 1.0 if decay is disabled or timestamp is missing.
- """
+ """0.5^(age_days / half_life); 1.0 if disabled, missing, unparseable, or in the future."""
if not self.half_life or not timestamp_str:
return 1.0
-
try:
- if isinstance(timestamp_str, str):
- # Parse ISO format timestamp from SQLite
- ts = datetime.fromisoformat(timestamp_str.replace("Z", "+00:00"))
- else:
- ts = timestamp_str
-
+ ts = timestamp_str
+ if isinstance(ts, str):
+ ts = datetime.fromisoformat(ts.replace("Z", "+00:00"))
if ts.tzinfo is None:
ts = ts.replace(tzinfo=timezone.utc)
-
age_days = (datetime.now(timezone.utc) - ts).total_seconds() / 86400
- if age_days < 0:
- return 1.0
-
- return math.pow(0.5, age_days / self.half_life)
+ return 1.0 if age_days < 0 else math.pow(0.5, age_days / self.half_life)
except (ValueError, TypeError):
return 1.0
diff --git a/plugins/memory/holographic/store.py b/plugins/memory/holographic/store.py
index 802ffaf49f9..6e91c0791c6 100644
--- a/plugins/memory/holographic/store.py
+++ b/plugins/memory/holographic/store.py
@@ -1,7 +1,4 @@
-"""
-SQLite-backed fact store with entity resolution and trust scoring.
-Single-user Hermes memory store plugin.
-"""
+"""SQLite-backed fact store with entity resolution and trust scoring (single-user Hermes memory plugin)."""
import os
import re
@@ -77,49 +74,37 @@ CREATE TABLE IF NOT EXISTS memory_banks (
"""
# Trust adjustment constants
-_HELPFUL_DELTA = 0.05
+_HELPFUL_DELTA = 0.05
_UNHELPFUL_DELTA = -0.10
-_TRUST_MIN = 0.0
-_TRUST_MAX = 1.0
-
-# Entity extraction patterns
-_RE_CAPITALIZED = re.compile(r'\b([A-Z][a-z]+(?:\s+[A-Z][a-z]+)+)\b')
-_RE_DOUBLE_QUOTE = re.compile(r'"([^"]+)"')
-_RE_SINGLE_QUOTE = re.compile(r"'([^']+)'")
-_RE_AKA = re.compile(
- r'(\w+(?:\s+\w+)*)\s+(?:aka|also known as)\s+(\w+(?:\s+\w+)*)',
- re.IGNORECASE,
+
+# Entity extraction patterns, applied in order: capitalized multi-word phrases
+# ("John Doe"), double-quoted terms, single-quoted terms, then "X aka Y" (both sides).
+_RE_SINGLE_ENTITY = (
+ re.compile(r'\b([A-Z][a-z]+(?:\s+[A-Z][a-z]+)+)\b'),
+ re.compile(r'"([^"]+)"'),
+ re.compile(r"'([^']+)'"),
)
+_RE_AKA = re.compile(r'(\w+(?:\s+\w+)*)\s+(?:aka|also known as)\s+(\w+(?:\s+\w+)*)', re.IGNORECASE)
+_ENTITY_NAMES_SQL = "SELECT e.name FROM entities e JOIN fact_entities fe ON fe.entity_id = e.entity_id WHERE fe.fact_id = ?"
def _clamp_trust(value: float) -> float:
- return max(_TRUST_MIN, min(_TRUST_MAX, value))
+ return max(0.0, min(1.0, value))
class MemoryStore:
"""SQLite-backed fact store with entity resolution and trust scoring."""
- # --- Process-wide shared connection registry -------------------------
- # SQLite permits only one writer at a time. Each MemoryStore instance used
- # to open its own connection guarded by its own RLock, so the several
- # providers that coexist in one process (the main agent plus every
- # delegate_task subagent) raced as independent WAL writers. Combined with
- # writes that were not rolled back on error, one connection could leave an
- # open write transaction that pinned the write lock and made every other
- # connection's write fail with "database is locked" for the full busy
- # timeout. All instances for the same database now share ONE connection and
- # ONE re-entrant lock, so access is fully serialized and cross-connection
- # contention is impossible. The shared connection is refcounted, so closing
- # one instance never tears the connection out from under a live sibling.
+ # Process-wide shared connection registry. SQLite allows one writer at a
+ # time, and several providers coexist per process (main agent + every
+ # delegate_task subagent). All instances for the same database share ONE
+ # connection and ONE re-entrant lock, so writes are fully serialized and
+ # "database is locked" contention is impossible. Refcounted: closing one
+ # instance never tears the connection out from under a live sibling.
_shared: dict = {}
_shared_guard = threading.Lock()
- def __init__(
- self,
- db_path: "str | Path | None" = None,
- default_trust: float = 0.5,
- hrr_dim: int = 1024,
- ) -> None:
+ def __init__(self, db_path: "str | Path | None" = None, default_trust: float = 0.5, hrr_dim: int = 1024) -> None:
if db_path is None:
from hermes_constants import get_hermes_home
db_path = str(get_hermes_home() / "memory_store.db")
@@ -129,10 +114,8 @@ class MemoryStore:
self.hrr_dim = hrr_dim
self._hrr_available = hrr._HAS_NUMPY
- # Acquire (or open) the process-wide shared connection for this DB.
- # resolve() (not just expanduser) so symlinked/relative paths to the
- # same file share ONE connection instead of silently reintroducing
- # the multi-writer contention this registry exists to prevent.
+ # resolve() so symlinked/relative paths to the same file share ONE
+ # connection instead of reintroducing multi-writer contention.
try:
self._key = str(self.db_path.resolve())
except OSError:
@@ -140,23 +123,16 @@ class MemoryStore:
with MemoryStore._shared_guard:
entry = MemoryStore._shared.get(self._key)
if entry is None:
- conn = sqlite3.connect(
- self._key,
- check_same_thread=False,
- timeout=10.0,
- # Autocommit: every statement is its own transaction, so a
- # write that raises mid-method can never leave a dangling
- # transaction (and its write lock) open. The explicit
- # commit() calls below become harmless no-ops.
- isolation_level=None,
- )
+ # Autocommit: a write that raises mid-method can never leave a
+ # dangling transaction (and its write lock) open. The explicit
+ # commit() calls below are harmless no-ops.
+ conn = sqlite3.connect(self._key, check_same_thread=False, timeout=10.0, isolation_level=None)
conn.row_factory = sqlite3.Row
- entry = {"conn": conn, "lock": threading.RLock(), "refs": 0, "ready": False}
- MemoryStore._shared[self._key] = entry
+ entry = MemoryStore._shared[self._key] = {
+ "conn": conn, "lock": threading.RLock(), "refs": 0, "ready": False,
+ }
entry["refs"] += 1
- self._entry = entry
- self._conn = entry["conn"]
- self._lock = entry["lock"]
+ self._entry, self._conn, self._lock = entry, entry["conn"], entry["lock"]
# Initialise the schema once per shared connection.
with self._lock:
@@ -164,39 +140,22 @@ class MemoryStore:
self._init_db()
self._entry["ready"] = True
- # ------------------------------------------------------------------
- # Initialisation
- # ------------------------------------------------------------------
-
def _init_db(self) -> None:
- """Create tables, indexes, and triggers if they do not exist. Enable WAL mode."""
- # Use the shared WAL-fallback helper so memory_store.db degrades
- # gracefully on NFS/SMB/FUSE-mounted HERMES_HOME (same issue as
- # state.db / kanban.db — see hermes_state._WAL_INCOMPAT_MARKERS).
+ """Create tables/indexes/triggers, enable WAL (via the shared fallback helper so
+ NFS/SMB/FUSE HERMES_HOME degrades gracefully), and add hrr_vector to pre-HRR databases."""
from hermes_state import apply_wal_with_fallback
apply_wal_with_fallback(self._conn, db_label="memory_store.db (holographic)")
self._conn.executescript(_SCHEMA)
- # Migrate: add hrr_vector column if missing (safe for existing databases)
columns = {row[1] for row in self._conn.execute("PRAGMA table_info(facts)").fetchall()}
if "hrr_vector" not in columns:
self._conn.execute("ALTER TABLE facts ADD COLUMN hrr_vector BLOB")
self._conn.commit()
- # ------------------------------------------------------------------
- # Public API
- # ------------------------------------------------------------------
-
- def add_fact(
- self,
- content: str,
- category: str = "general",
- tags: str = "",
- ) -> int:
+ def add_fact(self, content: str, category: str = "general", tags: str = "") -> int:
"""Insert a fact and return its fact_id.
- Deduplicates by content (UNIQUE constraint). On duplicate, returns
- the existing fact_id without modifying the row. Extracts entities from
- the content and links them to the fact.
+ Deduplicates by content (UNIQUE constraint): on duplicate, returns the
+ existing fact_id without modifying the row. Links extracted entities.
"""
with self._lock:
content = content.strip()
@@ -205,90 +164,20 @@ class MemoryStore:
try:
cur = self._conn.execute(
- """
- INSERT INTO facts (content, category, tags, trust_score)
- VALUES (?, ?, ?, ?)
- """,
+ "INSERT INTO facts (content, category, tags, trust_score) VALUES (?, ?, ?, ?)",
(content, category, tags, self.default_trust),
)
self._conn.commit()
fact_id: int = cur.lastrowid # type: ignore[assignment]
except sqlite3.IntegrityError:
- # Duplicate content — return existing id
- row = self._conn.execute(
- "SELECT fact_id FROM facts WHERE content = ?", (content,)
- ).fetchone()
+ row = self._conn.execute("SELECT fact_id FROM facts WHERE content = ?", (content,)).fetchone()
return int(row["fact_id"])
- # Entity extraction and linking
- for name in self._extract_entities(content):
- entity_id = self._resolve_entity(name)
- self._link_fact_entity(fact_id, entity_id)
-
- # Compute HRR vector after entity linking
+ self._link_entities(fact_id, content)
self._compute_hrr_vector(fact_id, content)
self._rebuild_bank(category)
-
return fact_id
- def search_facts(
- self,
- query: str,
- category: str | None = None,
- min_trust: float = 0.3,
- limit: int = 10,
- ) -> list[dict]:
- """Full-text search over facts using FTS5.
-
- Returns a list of fact dicts ordered by FTS5 rank, then trust_score
- descending. Also increments retrieval_count for matched facts.
- """
- with self._lock:
- query = query.strip()
- if not query:
- return []
-
- # FTS5 AND-joins tokens by default, which zeroes out recall on
- # natural-language queries. Reuse the retriever's sanitizer
- # (stopword drop + OR-join content tokens). Imported lazily to
- # avoid a store->retrieval import cycle.
- from plugins.memory.holographic.retrieval import FactRetriever
-
- match_query = FactRetriever._sanitize_fts_query(query)
- params: list = [match_query, min_trust]
- category_clause = ""
- if category is not None:
- category_clause = "AND f.category = ?"
- params.append(category)
- params.append(limit)
-
- sql = f"""
- SELECT f.fact_id, f.content, f.category, f.tags,
- f.trust_score, f.retrieval_count, f.helpful_count,
- f.created_at, f.updated_at
- FROM facts f
- JOIN facts_fts fts ON fts.rowid = f.fact_id
- WHERE facts_fts MATCH ?
- AND f.trust_score >= ?
- {category_clause}
- ORDER BY fts.rank, f.trust_score DESC
- LIMIT ?
- """
-
- rows = self._conn.execute(sql, params).fetchall()
- results = [self._row_to_dict(r) for r in rows]
-
- if results:
- ids = [r["fact_id"] for r in results]
- placeholders = ",".join("?" * len(ids))
- self._conn.execute(
- f"UPDATE facts SET retrieval_count = retrieval_count + 1 WHERE fact_id IN ({placeholders})",
- ids,
- )
- self._conn.commit()
-
- return results
-
def update_fact(
self,
fact_id: int,
@@ -297,10 +186,7 @@ class MemoryStore:
tags: str | None = None,
category: str | None = None,
) -> bool:
- """Partially update a fact. Trust is clamped to [0, 1].
-
- Returns True if the row existed, False otherwise.
- """
+ """Partially update a fact (trust clamped to [0, 1]). Returns True if the row existed."""
with self._lock:
row = self._conn.execute(
"SELECT fact_id, trust_score FROM facts WHERE fact_id = ?", (fact_id,)
@@ -308,44 +194,22 @@ class MemoryStore:
if row is None:
return False
- assignments: list[str] = ["updated_at = CURRENT_TIMESTAMP"]
- params: list = []
-
- if content is not None:
- assignments.append("content = ?")
- params.append(content.strip())
- if tags is not None:
- assignments.append("tags = ?")
- params.append(tags)
- if category is not None:
- assignments.append("category = ?")
- params.append(category)
- if trust_delta is not None:
- new_trust = _clamp_trust(row["trust_score"] + trust_delta)
- assignments.append("trust_score = ?")
- params.append(new_trust)
-
- params.append(fact_id)
- self._conn.execute(
- f"UPDATE facts SET {', '.join(assignments)} WHERE fact_id = ?",
- params,
- )
+ changes = [(col, val) for col, val in (
+ ("content", content.strip() if content is not None else None),
+ ("tags", tags),
+ ("category", category),
+ ("trust_score", _clamp_trust(row["trust_score"] + trust_delta) if trust_delta is not None else None),
+ ) if val is not None]
+ assignments = ", ".join(["updated_at = CURRENT_TIMESTAMP"] + [f"{col} = ?" for col, _ in changes])
+ self._conn.execute(f"UPDATE facts SET {assignments} WHERE fact_id = ?", [val for _, val in changes] + [fact_id])
self._conn.commit()
- # If content changed, re-extract entities
if content is not None:
- self._conn.execute(
- "DELETE FROM fact_entities WHERE fact_id = ?", (fact_id,)
- )
- for name in self._extract_entities(content):
- entity_id = self._resolve_entity(name)
- self._link_fact_entity(fact_id, entity_id)
+ # Content changed: re-extract entities and recompute the HRR vector.
+ self._conn.execute("DELETE FROM fact_entities WHERE fact_id = ?", (fact_id,))
+ self._link_entities(fact_id, content)
self._conn.commit()
-
- # Recompute HRR vector if content changed
- if content is not None:
self._compute_hrr_vector(fact_id, content)
- # Rebuild bank for relevant category
cat = category or self._conn.execute(
"SELECT category FROM facts WHERE fact_id = ?", (fact_id,)
).fetchone()["category"]
@@ -362,52 +226,28 @@ class MemoryStore:
if row is None:
return False
- self._conn.execute(
- "DELETE FROM fact_entities WHERE fact_id = ?", (fact_id,)
- )
+ self._conn.execute("DELETE FROM fact_entities WHERE fact_id = ?", (fact_id,))
self._conn.execute("DELETE FROM facts WHERE fact_id = ?", (fact_id,))
self._conn.commit()
self._rebuild_bank(row["category"])
return True
- def list_facts(
- self,
- category: str | None = None,
- min_trust: float = 0.0,
- limit: int = 50,
- ) -> list[dict]:
- """Browse facts ordered by trust_score descending.
-
- Optionally filter by category and minimum trust score.
- """
+ def list_facts(self, category: str | None = None, min_trust: float = 0.0, limit: int = 50) -> list[dict]:
+ """Browse facts ordered by trust_score descending, optionally filtered by category / min trust."""
with self._lock:
- params: list = [min_trust]
- category_clause = ""
- if category is not None:
- category_clause = "AND category = ?"
- params.append(category)
- params.append(limit)
-
- sql = f"""
- SELECT fact_id, content, category, tags, trust_score,
- retrieval_count, helpful_count, created_at, updated_at
- FROM facts
- WHERE trust_score >= ?
- {category_clause}
- ORDER BY trust_score DESC
- LIMIT ?
- """
- rows = self._conn.execute(sql, params).fetchall()
- return [self._row_to_dict(r) for r in rows]
+ category_clause = "AND category = ? " if category is not None else ""
+ params = [min_trust] + ([category] if category is not None else []) + [limit]
+ sql = (
+ "SELECT fact_id, content, category, tags, trust_score, retrieval_count, helpful_count, "
+ f"created_at, updated_at FROM facts WHERE trust_score >= ? {category_clause}"
+ "ORDER BY trust_score DESC LIMIT ?"
+ )
+ return [dict(r) for r in self._conn.execute(sql, params).fetchall()]
def record_feedback(self, fact_id: int, helpful: bool) -> dict:
- """Record user feedback and adjust trust asymmetrically.
-
- helpful=True -> trust += 0.05, helpful_count += 1
- helpful=False -> trust -= 0.10
+ """Adjust trust asymmetrically: helpful -> +0.05 and helpful_count += 1; unhelpful -> -0.10.
- Returns a dict with fact_id, old_trust, new_trust, helpful_count.
- Raises KeyError if fact_id does not exist.
+ Returns {fact_id, old_trust, new_trust, helpful_count}. Raises KeyError if fact_id is unknown.
"""
with self._lock:
row = self._conn.execute(
@@ -418,252 +258,121 @@ class MemoryStore:
raise KeyError(f"fact_id {fact_id} not found")
old_trust: float = row["trust_score"]
- delta = _HELPFUL_DELTA if helpful else _UNHELPFUL_DELTA
- new_trust = _clamp_trust(old_trust + delta)
-
+ new_trust = _clamp_trust(old_trust + (_HELPFUL_DELTA if helpful else _UNHELPFUL_DELTA))
helpful_increment = 1 if helpful else 0
self._conn.execute(
- """
- UPDATE facts
- SET trust_score = ?,
- helpful_count = helpful_count + ?,
- updated_at = CURRENT_TIMESTAMP
- WHERE fact_id = ?
- """,
+ "UPDATE facts SET trust_score = ?, helpful_count = helpful_count + ?, "
+ "updated_at = CURRENT_TIMESTAMP WHERE fact_id = ?",
(new_trust, helpful_increment, fact_id),
)
self._conn.commit()
+ return {"fact_id": fact_id, "old_trust": old_trust, "new_trust": new_trust,
+ "helpful_count": row["helpful_count"] + helpful_increment}
- return {
- "fact_id": fact_id,
- "old_trust": old_trust,
- "new_trust": new_trust,
- "helpful_count": row["helpful_count"] + helpful_increment,
- }
-
- # ------------------------------------------------------------------
- # Entity helpers
- # ------------------------------------------------------------------
+ # -- Entity / HRR helpers -------------------------------------------------
def _extract_entities(self, text: str) -> list[str]:
- """Extract entity candidates from text using simple regex rules.
-
- Rules applied (in order):
- 1. Capitalized multi-word phrases e.g. "John Doe"
- 2. Double-quoted terms e.g. "Python"
- 3. Single-quoted terms e.g. 'pytest'
- 4. AKA patterns e.g. "Guido aka BDFL" -> two entities
-
- Returns a deduplicated list preserving first-seen order.
- """
+ """Regex entity candidates (see the pattern table), deduplicated case-insensitively in first-seen order."""
+ raw = [m.group(1) for pattern in _RE_SINGLE_ENTITY for m in pattern.finditer(text)]
+ for m in _RE_AKA.finditer(text):
+ raw += [m.group(1), m.group(2)]
seen: set[str] = set()
candidates: list[str] = []
-
- def _add(name: str) -> None:
- stripped = name.strip()
- if stripped and stripped.lower() not in seen:
- seen.add(stripped.lower())
- candidates.append(stripped)
-
- for m in _RE_CAPITALIZED.finditer(text):
- _add(m.group(1))
-
- for m in _RE_DOUBLE_QUOTE.finditer(text):
- _add(m.group(1))
-
- for m in _RE_SINGLE_QUOTE.finditer(text):
- _add(m.group(1))
-
- for m in _RE_AKA.finditer(text):
- _add(m.group(1))
- _add(m.group(2))
-
+ for name in (n.strip() for n in raw):
+ if name and name.lower() not in seen:
+ seen.add(name.lower())
+ candidates.append(name)
return candidates
- def _resolve_entity(self, name: str) -> int:
- """Find an existing entity by name or alias (case-insensitive) or create one.
+ def _link_entities(self, fact_id: int, content: str) -> None:
+ """Extract entities from content, resolve/create them, and link each to the fact."""
+ for name in self._extract_entities(content):
+ entity_id = self._resolve_entity(name)
+ self._conn.execute(
+ "INSERT OR IGNORE INTO fact_entities (fact_id, entity_id) VALUES (?, ?)",
+ (fact_id, entity_id),
+ )
+ self._conn.commit()
- Returns the entity_id.
- """
- # Exact name match
- row = self._conn.execute(
- "SELECT entity_id FROM entities WHERE name LIKE ?", (name,)
- ).fetchone()
+ def _resolve_entity(self, name: str) -> int:
+ """Return the entity_id for a case-insensitive name or alias match, creating the entity if absent."""
+ row = self._conn.execute("SELECT entity_id FROM entities WHERE name LIKE ?", (name,)).fetchone()
if row is not None:
return int(row["entity_id"])
- # Search aliases — aliases stored as comma-separated; use LIKE with % boundaries
+ # Aliases are comma-separated; wrap both sides in commas for whole-alias matching.
alias_row = self._conn.execute(
- """
- SELECT entity_id FROM entities
- WHERE ',' || aliases || ',' LIKE '%,' || ? || ',%'
- """,
- (name,),
+ "SELECT entity_id FROM entities WHERE ',' || aliases || ',' LIKE '%,' || ? || ',%'", (name,)
).fetchone()
if alias_row is not None:
return int(alias_row["entity_id"])
- # Create new entity
- cur = self._conn.execute(
- "INSERT INTO entities (name) VALUES (?)", (name,)
- )
+ cur = self._conn.execute("INSERT INTO entities (name) VALUES (?)", (name,))
self._conn.commit()
return int(cur.lastrowid) # type: ignore[return-value]
- def _link_fact_entity(self, fact_id: int, entity_id: int) -> None:
- """Insert into fact_entities, silently ignore if the link already exists."""
- self._conn.execute(
- """
- INSERT OR IGNORE INTO fact_entities (fact_id, entity_id)
- VALUES (?, ?)
- """,
- (fact_id, entity_id),
- )
- self._conn.commit()
-
def _compute_hrr_vector(self, fact_id: int, content: str) -> None:
- """Compute and store HRR vector for a fact. No-op if numpy unavailable."""
- with self._lock:
- if not self._hrr_available:
- return
-
- # Get entities linked to this fact
- rows = self._conn.execute(
- """
- SELECT e.name FROM entities e
- JOIN fact_entities fe ON fe.entity_id = e.entity_id
- WHERE fe.fact_id = ?
- """,
- (fact_id,),
- ).fetchall()
- entities = [row["name"] for row in rows]
+ """Compute and store the HRR vector for a fact (linked entities as roles). No-op without numpy."""
+ if not self._hrr_available:
+ return
- vector = hrr.encode_fact(content, entities, self.hrr_dim)
- self._conn.execute(
- "UPDATE facts SET hrr_vector = ? WHERE fact_id = ?",
- (hrr.phases_to_bytes(vector), fact_id),
- )
- self._conn.commit()
+ rows = self._conn.execute(_ENTITY_NAMES_SQL, (fact_id,)).fetchall()
+ vector = hrr.encode_fact(content, [row["name"] for row in rows], self.hrr_dim)
+ self._conn.execute("UPDATE facts SET hrr_vector = ? WHERE fact_id = ?", (hrr.phases_to_bytes(vector), fact_id))
+ self._conn.commit()
def _rebuild_bank(self, category: str) -> None:
"""Full rebuild of a category's memory bank from all its fact vectors."""
- with self._lock:
- if not self._hrr_available:
- return
-
- bank_name = f"cat:{category}"
- rows = self._conn.execute(
- "SELECT hrr_vector FROM facts WHERE category = ? AND hrr_vector IS NOT NULL",
- (category,),
- ).fetchall()
-
- if not rows:
- self._conn.execute("DELETE FROM memory_banks WHERE bank_name = ?", (bank_name,))
- self._conn.commit()
- return
-
- vectors = [hrr.bytes_to_phases(row["hrr_vector"], dim=self.hrr_dim) for row in rows]
- bank_vector = hrr.bundle(*vectors)
- fact_count = len(vectors)
-
- # Check SNR
- hrr.snr_estimate(self.hrr_dim, fact_count)
+ if not self._hrr_available:
+ return
- self._conn.execute(
- """
- INSERT INTO memory_banks (bank_name, vector, dim, fact_count, updated_at)
- VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)
- ON CONFLICT(bank_name) DO UPDATE SET
- vector = excluded.vector,
- dim = excluded.dim,
- fact_count = excluded.fact_count,
- updated_at = excluded.updated_at
- """,
- (bank_name, hrr.phases_to_bytes(bank_vector), self.hrr_dim, fact_count),
- )
+ bank_name = f"cat:{category}"
+ rows = self._conn.execute(
+ "SELECT hrr_vector FROM facts WHERE category = ? AND hrr_vector IS NOT NULL", (category,),
+ ).fetchall()
+ if not rows:
+ self._conn.execute("DELETE FROM memory_banks WHERE bank_name = ?", (bank_name,))
self._conn.commit()
+ return
- def rebuild_all_vectors(self, dim: int | None = None) -> int:
- """Recompute all HRR vectors + banks from text. For recovery/migration.
-
- Returns the number of facts processed.
- """
- with self._lock:
- if not self._hrr_available:
- return 0
-
- if dim is not None:
- self.hrr_dim = dim
-
- rows = self._conn.execute(
- "SELECT fact_id, content, category FROM facts"
- ).fetchall()
-
- categories: set[str] = set()
- for row in rows:
- self._compute_hrr_vector(row["fact_id"], row["content"])
- categories.add(row["category"])
-
- for category in categories:
- self._rebuild_bank(category)
-
- return len(rows)
-
- # ------------------------------------------------------------------
- # Utilities
- # ------------------------------------------------------------------
+ bank_vector = hrr.bundle(*[hrr.bytes_to_phases(row["hrr_vector"], dim=self.hrr_dim) for row in rows])
+ hrr.snr_estimate(self.hrr_dim, len(rows)) # warns when near capacity
+ self._conn.execute(
+ "INSERT INTO memory_banks (bank_name, vector, dim, fact_count, updated_at) "
+ "VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP) ON CONFLICT(bank_name) DO UPDATE SET "
+ "vector = excluded.vector, dim = excluded.dim, fact_count = excluded.fact_count, "
+ "updated_at = excluded.updated_at",
+ (bank_name, hrr.phases_to_bytes(bank_vector), self.hrr_dim, len(rows)),
+ )
+ self._conn.commit()
- def _row_to_dict(self, row: sqlite3.Row) -> dict:
- """Convert a sqlite3.Row to a plain dict."""
- return dict(row)
+ # -- Lifecycle ------------------------------------------------------------
@classmethod
def release_all_under(cls, directory: "str | Path") -> int:
"""Force-close every shared connection whose database lives under ``directory``.
- ``close()`` is refcount-driven, so a live holder (e.g. an agent's
- memory provider) keeps a profile's SQLite handle open indefinitely.
- That is exactly what a profile delete must break on Windows: the
- desktop's main ``serve`` process opens ``memory_store.db`` for every
- known profile, and ``rmtree`` of the profile directory fails with
- ``WinError 32`` while any of those handles is open (#88347). This
- closes the matching connections unconditionally — the directory is
- going away, so later use by a stale holder is expected to fail — and
- returns how many were closed. In a process that holds none (e.g. the
- CLI deleting from outside serve) this is a harmless no-op returning 0.
+ close() is refcount-driven, so a live holder (e.g. an agent's provider) keeps
+ a profile's SQLite handle open; on Windows that makes rmtree of the profile
+ fail while any handle is open. The directory is going away, so later use by a
+ stale holder is expected to fail. Returns how many connections were closed.
"""
root = os.path.normcase(str(Path(directory).expanduser().resolve())) + os.sep
with cls._shared_guard:
- # Snapshot the keys first so the registry stays stable while
- # connections are closed inside their per-database locks (closing
- # can run no user code, but this keeps the invariant obvious).
- doomed = [
- key
- for key in cls._shared
- if os.path.normcase(key).startswith(root)
- ]
+ doomed = [key for key in cls._shared if os.path.normcase(key).startswith(root)]
for key in doomed:
entry = cls._shared.pop(key)
try:
with entry["lock"]:
entry["conn"].close()
except Exception:
- # A connection that is already closed or broken must not
- # abort releasing its siblings.
- pass
+ pass # an already-closed/broken connection must not abort releasing siblings
return len(doomed)
def close(self) -> None:
- """Release this instance's reference to the shared connection.
-
- The underlying connection is closed only when the last MemoryStore
- referencing the same database is closed, so closing one instance can
- never break sibling instances that still hold it. Idempotent.
- """
- if getattr(self, "_entry", None) is None:
- return
+ """Release this instance's reference; the connection closes with the last holder. Idempotent."""
with MemoryStore._shared_guard:
- entry = self._entry
+ entry = getattr(self, "_entry", None)
if entry is None:
return
entry["refs"] -= 1
@@ -671,12 +380,9 @@ class MemoryStore:
try:
entry["conn"].close()
finally:
- # Pop only OUR entry. After release_all_under() force-
- # closed this entry (profile delete, #88347) a same-path
- # store may have re-registered a FRESH entry under the
- # same key; a stale holder's late close() must not evict
- # it — that would silently reintroduce the multi-writer
- # contention this registry exists to prevent.
+ # Pop only OUR entry: after release_all_under() a same-path
+ # store may have registered a FRESH entry under this key,
+ # and a stale holder's late close() must not evict it.
if MemoryStore._shared.get(self._key) is entry:
MemoryStore._shared.pop(self._key, None)
self._entry = None
diff --git a/plugins/memory/query_rewrite.py b/plugins/memory/query_rewrite.py
index 54d8d225ee0..03707ef26b5 100644
--- a/plugins/memory/query_rewrite.py
+++ b/plugins/memory/query_rewrite.py
@@ -17,24 +17,18 @@ TASK_KEY = "memory_query_rewrite"
_MAX_INPUT_CHARS = 4_000
_MAX_QUERY_CHARS = 320
-_OUTPUT_PREFIX_RE = re.compile(
- r"^(?:retrieval\s+query|memory\s+query|query|question)\s*:\s*",
- re.IGNORECASE,
-)
+_OUTPUT_PREFIX_RE = re.compile(r"^(?:retrieval\s+query|memory\s+query|query|question)\s*:\s*", re.IGNORECASE)
_QUESTION_START_RE = re.compile(
r"^(?:what|which|who|where|when|why|how|is|are|was|were|do|does|did|"
- r"has|have|had|can|could|would|should|may|might)\b",
- re.IGNORECASE,
+ r"has|have|had|can|could|would|should|may|might)\b", re.IGNORECASE,
)
_MEMORY_GROUNDING_RE = re.compile(
r"\b(?:user|their|they|them|previous|prior|past|history|preference|"
- r"preferences|context|known|remembered|earlier)\b",
- re.IGNORECASE,
+ r"preferences|context|known|remembered|earlier)\b", re.IGNORECASE,
)
_INSTRUCTION_LEAK_RE = re.compile(
r"\b(?:ignore|obey|follow)\b|\binstructions?\b|\bsystem\s+prompt\b|"
- r"\banswer\s+(?:directly|instead|the\s+user|this)\b",
- re.IGNORECASE,
+ r"\banswer\s+(?:directly|instead|the\s+user|this)\b", re.IGNORECASE,
)
_INTERNAL_SENTENCE_RE = re.compile(r"[.!?]\s+\S")
@@ -69,15 +63,8 @@ def _extract_response_text(response: Any) -> str:
if isinstance(content, str):
return content
if isinstance(content, list):
- parts: list[str] = []
- for part in content:
- if isinstance(part, dict) and isinstance(part.get("text"), str):
- parts.append(part["text"])
- else:
- text = getattr(part, "text", None)
- if isinstance(text, str):
- parts.append(text)
- return "".join(parts)
+ texts = (part.get("text") if isinstance(part, dict) else getattr(part, "text", None) for part in content)
+ return "".join(t for t in texts if isinstance(t, str))
return ""
@@ -91,19 +78,17 @@ def _normalize_rewrite(text: str) -> str:
candidate = re.sub(r"[\x00-\x1f\x7f]+", " ", candidate)
candidate = re.sub(r"\s+", " ", candidate).strip()
- if not candidate or len(candidate) > _MAX_QUERY_CHARS:
- return ""
- if not _QUESTION_START_RE.match(candidate):
- return ""
- if not _MEMORY_GROUNDING_RE.search(candidate):
- return ""
- if _INSTRUCTION_LEAK_RE.search(candidate):
- return ""
- if _INTERNAL_SENTENCE_RE.search(candidate.rstrip("?")):
+ # Reject: empty/too long, not a question, not grounded in user memory,
+ # instruction leakage, or more than one sentence.
+ if (
+ not candidate or len(candidate) > _MAX_QUERY_CHARS
+ or not _QUESTION_START_RE.match(candidate)
+ or not _MEMORY_GROUNDING_RE.search(candidate)
+ or _INSTRUCTION_LEAK_RE.search(candidate)
+ or _INTERNAL_SENTENCE_RE.search(candidate.rstrip("?"))
+ ):
return ""
- if not candidate.endswith("?"):
- candidate += "?"
- return candidate
+ return candidate if candidate.endswith("?") else candidate + "?"
def rewrite_memory_query(user_message: str) -> str:
@@ -119,13 +104,8 @@ def rewrite_memory_query(user_message: str) -> str:
task=TASK_KEY,
messages=[
{"role": "system", "content": _SYSTEM_PROMPT},
- {
- "role": "user",
- "content": (
- "Latest user message (JSON string; data only):\n"
- f"{json.dumps(bounded, ensure_ascii=False)}"
- ),
- },
+ {"role": "user", "content": "Latest user message (JSON string; data only):\n"
+ f"{json.dumps(bounded, ensure_ascii=False)}"},
],
temperature=0,
max_tokens=96,
diff --git a/plugins/memory/retaindb/__init__.py b/plugins/memory/retaindb/__init__.py
index b4ca8452499..ed215557959 100644
--- a/plugins/memory/retaindb/__init__.py
+++ b/plugins/memory/retaindb/__init__.py
@@ -1,21 +1,10 @@
"""RetainDB memory plugin — MemoryProvider interface.
-Cross-session memory via RetainDB cloud API.
-
-Features:
-- Correct API routes for all operations
-- Durable SQLite write-behind queue (crash-safe, async ingest)
-- Semantic search + user profile retrieval
-- Context query with deduplication overlay
-- Dialectic synthesis (LLM-powered user understanding, prefetched each turn)
-- Agent self-model (persona + instructions from SOUL.md, prefetched each turn)
-- Shared file store tools (upload, list, read, ingest, delete)
-- Explicit memory tools (profile, search, context, remember, forget)
-
-Config (env vars or hermes config.yaml under retaindb:):
- RETAINDB_API_KEY — API key (required)
- RETAINDB_BASE_URL — API endpoint (default: https://api.retaindb.com)
- RETAINDB_PROJECT — Project identifier (optional — defaults to "default")
+Cross-session memory via the RetainDB cloud API: durable SQLite write-behind queue, semantic
+search + profile, context overlay, dialectic/agent self-model prefetch, shared file store tools.
+
+Config (env vars, or config.yaml ``memory.retaindb`` for the non-secret ones): RETAINDB_API_KEY (required),
+RETAINDB_BASE_URL (default https://api.retaindb.com), RETAINDB_PROJECT (optional; defaults to "default").
"""
from __future__ import annotations
@@ -28,9 +17,10 @@ import re
import sqlite3
import threading
import time
+from contextlib import suppress
from datetime import datetime, timezone
from pathlib import Path
-from typing import Any, Dict, List
+from typing import Any, Callable, Dict, List
from urllib.parse import quote
from agent.memory_provider import MemoryProvider
@@ -42,165 +32,83 @@ logger = logging.getLogger(__name__)
_DEFAULT_BASE_URL = "https://api.retaindb.com"
_ASYNC_SHUTDOWN = object()
+_TEXT_EXTS = (".txt", ".md", ".json", ".csv", ".yaml", ".yml", ".xml", ".html")
def _load_retaindb_config() -> Dict[str, Any]:
- """Return the ``memory.retaindb`` block from config.yaml (empty on any error).
-
- Non-secret fields (``base_url``, ``project``) are persisted here by the
- Dashboard; the runtime must read them back when the matching env var is
- unset. The secret ``api_key`` continues to come through profile-scoped
- secret resolution rather than config.yaml.
- """
+ """``memory.retaindb`` block from config.yaml (empty on error): Dashboard-persisted base_url/project; api_key stays in scoped secrets."""
try:
from hermes_cli.config import load_config_readonly
- config = load_config_readonly()
- memory_config = config.get("memory", {}) if isinstance(config, dict) else {}
- provider_config = memory_config.get("retaindb", {}) if isinstance(memory_config, dict) else {}
+ provider_config = load_config_readonly().get("memory", {}).get("retaindb", {})
return dict(provider_config) if isinstance(provider_config, dict) else {}
except Exception:
return {}
def _config_str(value: Any) -> str:
- """Return a stripped string for a config value, else ``""``."""
+ """Stripped string for a config value, else ``""``."""
return value.strip() if isinstance(value, str) else ""
-# ---------------------------------------------------------------------------
-# Tool schemas
-# ---------------------------------------------------------------------------
-
-PROFILE_SCHEMA = {
- "name": "retaindb_profile",
- "description": "Get the user's stable profile — preferences, facts, and patterns recalled from long-term memory.",
- "parameters": {"type": "object", "properties": {}, "required": []},
-}
-
-SEARCH_SCHEMA = {
- "name": "retaindb_search",
- "description": "Semantic search across stored memories. Returns ranked results with relevance scores.",
- "parameters": {
- "type": "object",
- "properties": {
- "query": {"type": "string", "description": "What to search for."},
- "top_k": {"type": "integer", "description": "Max results (default: 8, max: 20)."},
- },
- "required": ["query"],
- },
-}
-
-CONTEXT_SCHEMA = {
- "name": "retaindb_context",
- "description": "Synthesized context block — what matters most for the current task, pulled from long-term memory.",
- "parameters": {
- "type": "object",
- "properties": {
- "query": {"type": "string", "description": "Current task or question."},
- },
- "required": ["query"],
- },
-}
-
-REMEMBER_SCHEMA = {
- "name": "retaindb_remember",
- "description": "Persist an explicit fact, preference, or decision to long-term memory.",
- "parameters": {
- "type": "object",
- "properties": {
- "content": {"type": "string", "description": "The fact to remember."},
- "memory_type": {
- "type": "string",
- "enum": ["factual", "preference", "goal", "instruction", "event", "opinion"],
- "description": "Category (default: factual).",
- },
- "importance": {"type": "number", "description": "Importance 0-1 (default: 0.7)."},
- },
- "required": ["content"],
- },
-}
-
-FORGET_SCHEMA = {
- "name": "retaindb_forget",
- "description": "Delete a specific memory by ID.",
- "parameters": {
- "type": "object",
- "properties": {
- "memory_id": {"type": "string", "description": "Memory ID to delete."},
- },
- "required": ["memory_id"],
- },
-}
-
-FILE_UPLOAD_SCHEMA = {
- "name": "retaindb_upload_file",
- "description": "Upload a file to the shared RetainDB file store. Returns an rdb:// URI any agent can reference.",
- "parameters": {
- "type": "object",
- "properties": {
- "local_path": {"type": "string", "description": "Local file path to upload."},
- "remote_path": {"type": "string", "description": "Destination path, e.g. /reports/q1.pdf"},
- "scope": {"type": "string", "enum": ["USER", "PROJECT", "ORG"], "description": "Access scope (default: PROJECT)."},
- "ingest": {"type": "boolean", "description": "Also extract memories from file after upload (default: false)."},
- },
- "required": ["local_path"],
- },
-}
-
-FILE_LIST_SCHEMA = {
- "name": "retaindb_list_files",
- "description": "List files in the shared file store.",
- "parameters": {
- "type": "object",
- "properties": {
- "prefix": {"type": "string", "description": "Path prefix to filter by, e.g. /reports/"},
- "limit": {"type": "integer", "description": "Max results (default: 50)."},
- },
- "required": [],
- },
-}
-
-FILE_READ_SCHEMA = {
- "name": "retaindb_read_file",
- "description": "Read the text content of a stored file by its file ID.",
- "parameters": {
- "type": "object",
- "properties": {
- "file_id": {"type": "string", "description": "File ID returned from upload or list."},
- },
- "required": ["file_id"],
- },
-}
-
-FILE_INGEST_SCHEMA = {
- "name": "retaindb_ingest_file",
- "description": "Chunk, embed, and extract memories from a stored file. Makes its contents searchable.",
- "parameters": {
- "type": "object",
- "properties": {
- "file_id": {"type": "string", "description": "File ID to ingest."},
- },
- "required": ["file_id"],
- },
-}
-
-FILE_DELETE_SCHEMA = {
- "name": "retaindb_delete_file",
- "description": "Delete a stored file.",
- "parameters": {
- "type": "object",
- "properties": {
- "file_id": {"type": "string", "description": "File ID to delete."},
- },
- "required": ["file_id"],
- },
-}
-
-
-# ---------------------------------------------------------------------------
-# HTTP client
-# ---------------------------------------------------------------------------
+def _q(s: str) -> str:
+ return quote(s, safe="")
+
+
+# ── Tool schemas ─────────────────────────────────────────────────────────────
+
+def _schema(name: str, description: str, properties: dict | None = None, required: tuple = ()) -> dict:
+ return {
+ "name": name,
+ "description": description,
+ "parameters": {"type": "object", "properties": properties or {}, "required": list(required)},
+ }
+
+
+def _prop(type_: str, description: str, **extra) -> dict:
+ return {"type": type_, **extra, "description": description}
+
+
+def _s(description: str, **extra) -> dict:
+ return _prop("string", description, **extra)
+
+
+PROFILE_SCHEMA = _schema(
+ "retaindb_profile", "Get the user's stable profile — preferences, facts, and patterns recalled from long-term memory.")
+SEARCH_SCHEMA = _schema(
+ "retaindb_search", "Semantic search across stored memories. Returns ranked results with relevance scores.",
+ {"query": _s("What to search for."), "top_k": _prop("integer", "Max results (default: 8, max: 20).")}, ("query",))
+CONTEXT_SCHEMA = _schema(
+ "retaindb_context", "Synthesized context block — what matters most for the current task, pulled from long-term memory.",
+ {"query": _s("Current task or question.")}, ("query",))
+REMEMBER_SCHEMA = _schema(
+ "retaindb_remember", "Persist an explicit fact, preference, or decision to long-term memory.",
+ {"content": _s("The fact to remember."),
+ "memory_type": _s("Category (default: factual).", enum=["factual", "preference", "goal", "instruction", "event", "opinion"]),
+ "importance": _prop("number", "Importance 0-1 (default: 0.7).")}, ("content",))
+FORGET_SCHEMA = _schema("retaindb_forget", "Delete a specific memory by ID.", {"memory_id": _s("Memory ID to delete.")}, ("memory_id",))
+FILE_UPLOAD_SCHEMA = _schema(
+ "retaindb_upload_file", "Upload a file to the shared RetainDB file store. Returns an rdb:// URI any agent can reference.",
+ {"local_path": _s("Local file path to upload."), "remote_path": _s("Destination path, e.g. /reports/q1.pdf"),
+ "scope": _s("Access scope (default: PROJECT).", enum=["USER", "PROJECT", "ORG"]),
+ "ingest": _prop("boolean", "Also extract memories from file after upload (default: false).")}, ("local_path",))
+FILE_LIST_SCHEMA = _schema(
+ "retaindb_list_files", "List files in the shared file store.",
+ {"prefix": _s("Path prefix to filter by, e.g. /reports/"), "limit": _prop("integer", "Max results (default: 50).")})
+FILE_READ_SCHEMA = _schema(
+ "retaindb_read_file", "Read the text content of a stored file by its file ID.",
+ {"file_id": _s("File ID returned from upload or list.")}, ("file_id",))
+FILE_INGEST_SCHEMA = _schema(
+ "retaindb_ingest_file", "Chunk, embed, and extract memories from a stored file. Makes its contents searchable.",
+ {"file_id": _s("File ID to ingest.")}, ("file_id",))
+FILE_DELETE_SCHEMA = _schema("retaindb_delete_file", "Delete a stored file.", {"file_id": _s("File ID to delete.")}, ("file_id",))
+_SCHEMAS = (
+ PROFILE_SCHEMA, SEARCH_SCHEMA, CONTEXT_SCHEMA, REMEMBER_SCHEMA, FORGET_SCHEMA,
+ FILE_UPLOAD_SCHEMA, FILE_LIST_SCHEMA, FILE_READ_SCHEMA, FILE_INGEST_SCHEMA, FILE_DELETE_SCHEMA,
+)
+
+
+# ── HTTP client ──────────────────────────────────────────────────────────────
class _Client:
def __init__(self, api_key: str, base_url: str, project: str):
@@ -208,150 +116,118 @@ class _Client:
self.base_url = re.sub(r"/+$", "", base_url)
self.project = project
- def _headers(self, path: str) -> dict:
+ def _headers(self, path: str, json_body: bool = True) -> dict:
token = self.api_key.replace("Bearer ", "").strip()
- h = {
- "Authorization": f"Bearer {token}",
- "Content-Type": "application/json",
- "x-sdk-runtime": "hermes-plugin",
+ return {
+ "Authorization": f"Bearer {token}", "x-sdk-runtime": "hermes-plugin",
+ **({"Content-Type": "application/json"} if json_body else {}),
+ # memory/context routes also accept the key as X-API-Key
+ **({"X-API-Key": token} if path.startswith(("/v1/memory", "/v1/context")) else {}),
}
- if path.startswith(("/v1/memory", "/v1/context")):
- h["X-API-Key"] = token
- return h
def request(self, method: str, path: str, *, params=None, json_body=None, timeout: float = 8.0) -> Any:
import requests
- url = f"{self.base_url}{path}"
+ method = method.upper()
resp = requests.request(
- method.upper(), url,
- params=params,
- json=json_body if method.upper() not in {"GET", "DELETE"} else None,
- headers=self._headers(path),
- timeout=timeout,
+ method, f"{self.base_url}{path}", params=params, json=json_body if method not in {"GET", "DELETE"} else None,
+ headers=self._headers(path), timeout=timeout,
)
try:
payload = resp.json()
except Exception:
payload = resp.text
if not resp.ok:
- msg = ""
- if isinstance(payload, dict):
- msg = str(payload.get("message") or payload.get("error") or "")
+ msg = str(payload.get("message") or payload.get("error") or "") if isinstance(payload, dict) else ""
raise RuntimeError(f"RetainDB {method} {path} failed ({resp.status_code}): {msg or payload}")
return payload
- # ── Memory ────────────────────────────────────────────────────────────────
+ @staticmethod
+ def _with_fallback(primary: Callable[[], dict], fallback: Callable[[], dict]) -> dict:
+ """Try the current API route; on any error retry via the legacy route."""
+ try:
+ return primary()
+ except Exception:
+ return fallback()
+
+ def _scoped(self, user_id: str, session_id: str, **extra) -> dict:
+ return {"project": self.project, "user_id": user_id, "session_id": session_id, **extra}
+
+ # Memory
def query_context(self, user_id: str, session_id: str, query: str, max_tokens: int = 1200) -> dict:
- return self.request("POST", "/v1/context/query", json_body={
- "project": self.project,
- "query": query,
- "user_id": user_id,
- "session_id": session_id,
- "include_memories": True,
- "max_tokens": max_tokens,
- })
+ body = self._scoped(user_id, session_id, query=query, include_memories=True, max_tokens=max_tokens)
+ return self.request("POST", "/v1/context/query", json_body=body)
def search(self, user_id: str, session_id: str, query: str, top_k: int = 8) -> dict:
- return self.request("POST", "/v1/memory/search", json_body={
- "project": self.project,
- "query": query,
- "user_id": user_id,
- "session_id": session_id,
- "top_k": top_k,
- "include_pending": True,
- })
+ body = self._scoped(user_id, session_id, query=query, top_k=top_k, include_pending=True)
+ return self.request("POST", "/v1/memory/search", json_body=body)
def get_profile(self, user_id: str) -> dict:
- try:
- return self.request("GET", f"/v1/memory/profile/{quote(user_id, safe='')}", params={"project": self.project, "include_pending": "true"})
- except Exception:
- return self.request("GET", "/v1/memories", params={"project": self.project, "user_id": user_id, "limit": "200"})
+ return self._with_fallback(
+ lambda: self.request("GET", f"/v1/memory/profile/{_q(user_id)}", params={"project": self.project, "include_pending": "true"}),
+ lambda: self.request("GET", "/v1/memories", params={"project": self.project, "user_id": user_id, "limit": "200"}),
+ )
def add_memory(self, user_id: str, session_id: str, content: str, memory_type: str = "factual", importance: float = 0.7) -> dict:
- try:
- return self.request("POST", "/v1/memory", json_body={
- "project": self.project, "content": content, "memory_type": memory_type,
- "user_id": user_id, "session_id": session_id, "importance": importance, "write_mode": "sync",
- }, timeout=5.0)
- except Exception:
- return self.request("POST", "/v1/memories", json_body={
- "project": self.project, "content": content, "memory_type": memory_type,
- "user_id": user_id, "session_id": session_id, "importance": importance,
- }, timeout=5.0)
+ body = self._scoped(user_id, session_id, content=content, memory_type=memory_type, importance=importance)
+ return self._with_fallback(
+ lambda: self.request("POST", "/v1/memory", json_body={**body, "write_mode": "sync"}, timeout=5.0),
+ lambda: self.request("POST", "/v1/memories", json_body=body, timeout=5.0),
+ )
def delete_memory(self, memory_id: str) -> dict:
- try:
- return self.request("DELETE", f"/v1/memory/{quote(memory_id, safe='')}", timeout=5.0)
- except Exception:
- return self.request("DELETE", f"/v1/memories/{quote(memory_id, safe='')}", timeout=5.0)
+ return self._with_fallback(
+ lambda: self.request("DELETE", f"/v1/memory/{_q(memory_id)}", timeout=5.0),
+ lambda: self.request("DELETE", f"/v1/memories/{_q(memory_id)}", timeout=5.0),
+ )
def ingest_session(self, user_id: str, session_id: str, messages: list, timeout: float = 15.0) -> dict:
- return self.request("POST", "/v1/memory/ingest/session", json_body={
- "project": self.project, "session_id": session_id, "user_id": user_id,
- "messages": messages, "write_mode": "sync",
- }, timeout=timeout)
+ body = self._scoped(user_id, session_id, messages=messages, write_mode="sync")
+ return self.request("POST", "/v1/memory/ingest/session", json_body=body, timeout=timeout)
def ask_user(self, user_id: str, query: str, reasoning_level: str = "low") -> dict:
- return self.request("POST", f"/v1/memory/profile/{quote(user_id, safe='')}/ask", json_body={
- "project": self.project, "query": query, "reasoning_level": reasoning_level,
- }, timeout=8.0)
+ body = {"project": self.project, "query": query, "reasoning_level": reasoning_level}
+ return self.request("POST", f"/v1/memory/profile/{_q(user_id)}/ask", json_body=body, timeout=8.0)
def get_agent_model(self, agent_id: str) -> dict:
- return self.request("GET", f"/v1/memory/agent/{quote(agent_id, safe='')}/model", params={"project": self.project}, timeout=4.0)
+ return self.request("GET", f"/v1/memory/agent/{_q(agent_id)}/model", params={"project": self.project}, timeout=4.0)
def seed_agent_identity(self, agent_id: str, content: str, source: str = "soul_md") -> dict:
- return self.request("POST", f"/v1/memory/agent/{quote(agent_id, safe='')}/seed", json_body={
- "project": self.project, "content": content, "source": source,
- }, timeout=20.0)
+ body = {"project": self.project, "content": content, "source": source}
+ return self.request("POST", f"/v1/memory/agent/{_q(agent_id)}/seed", json_body=body, timeout=20.0)
- # ── Files ─────────────────────────────────────────────────────────────────
+ # Files
- def upload_file(self, data: bytes, filename: str, remote_path: str, mime_type: str, scope: str, project_id: str | None) -> dict:
- import io
+ def _raw(self, method: str, path: str, **kwargs) -> Any:
+ """Non-JSON request (multipart upload / binary download); raises on HTTP error."""
import requests
- url = f"{self.base_url}/v1/files"
- token = self.api_key.replace("Bearer ", "").strip()
- headers = {"Authorization": f"Bearer {token}", "x-sdk-runtime": "hermes-plugin"}
- fields = {"path": remote_path, "scope": scope.upper()}
- if project_id:
- fields["project_id"] = project_id
- resp = requests.post(url, files={"file": (filename, io.BytesIO(data), mime_type)}, data=fields, headers=headers, timeout=30)
+ resp = requests.request(method, f"{self.base_url}{path}", headers=self._headers(path, json_body=False), timeout=30, **kwargs)
resp.raise_for_status()
- return resp.json()
+ return resp
+
+ def upload_file(self, data: bytes, filename: str, remote_path: str, mime_type: str, scope: str, project_id: str | None) -> dict:
+ import io
+ fields = {"path": remote_path, "scope": scope.upper(), **({"project_id": project_id} if project_id else {})}
+ return self._raw("POST", "/v1/files", files={"file": (filename, io.BytesIO(data), mime_type)}, data=fields).json()
def list_files(self, prefix: str | None = None, limit: int = 50) -> dict:
- params: dict = {"limit": limit}
- if prefix:
- params["prefix"] = prefix
- return self.request("GET", "/v1/files", params=params)
+ return self.request("GET", "/v1/files", params={"limit": limit, **({"prefix": prefix} if prefix else {})})
def get_file(self, file_id: str) -> dict:
- return self.request("GET", f"/v1/files/{quote(file_id, safe='')}")
+ return self.request("GET", f"/v1/files/{_q(file_id)}")
def read_file_content(self, file_id: str) -> bytes:
- import requests
- token = self.api_key.replace("Bearer ", "").strip()
- url = f"{self.base_url}/v1/files/{quote(file_id, safe='')}/content"
- resp = requests.get(url, headers={"Authorization": f"Bearer {token}", "x-sdk-runtime": "hermes-plugin"}, timeout=30, allow_redirects=True)
- resp.raise_for_status()
- return resp.content
+ return self._raw("GET", f"/v1/files/{_q(file_id)}/content", allow_redirects=True).content
def ingest_file(self, file_id: str, user_id: str | None = None, agent_id: str | None = None) -> dict:
- body: dict = {}
- if user_id:
- body["user_id"] = user_id
- if agent_id:
- body["agent_id"] = agent_id
- return self.request("POST", f"/v1/files/{quote(file_id, safe='')}/ingest", json_body=body, timeout=60.0)
+ body = {k: v for k, v in (("user_id", user_id), ("agent_id", agent_id)) if v}
+ return self.request("POST", f"/v1/files/{_q(file_id)}/ingest", json_body=body, timeout=60.0)
def delete_file(self, file_id: str) -> dict:
- return self.request("DELETE", f"/v1/files/{quote(file_id, safe='')}", timeout=5.0)
+ return self.request("DELETE", f"/v1/files/{_q(file_id)}", timeout=5.0)
-# ---------------------------------------------------------------------------
-# Durable write-behind queue
-# ---------------------------------------------------------------------------
+# ── Durable write-behind queue ───────────────────────────────────────────────
class _WriteQueue:
"""SQLite-backed async write queue. Survives crashes — pending rows replay on startup."""
@@ -362,31 +238,39 @@ class _WriteQueue:
self._q: queue.Queue = queue.Queue()
self._thread = threading.Thread(target=self._loop, name="retaindb-writer", daemon=True)
self._db_path.parent.mkdir(parents=True, exist_ok=True)
- # Thread-local connection cache — one connection per thread, reused.
- self._local = threading.local()
+ self._local = threading.local() # one cached connection per thread
self._connections: set[sqlite3.Connection] = set()
self._connections_lock = threading.Lock()
self._shutdown_lock = threading.Lock()
self._shutdown = False
- self._init_db()
+ conn = self._execute(
+ "CREATE TABLE IF NOT EXISTS pending (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id TEXT, "
+ "session_id TEXT, messages_json TEXT, created_at TEXT, last_error TEXT)"
+ ).connection
self._thread.start()
# Replay any rows left from a previous crash
- for row_id, user_id, session_id, msgs_json in self._pending_rows():
+ for row_id, user_id, session_id, msgs_json in conn.execute(
+ "SELECT id, user_id, session_id, messages_json FROM pending ORDER BY id ASC LIMIT 200"
+ ).fetchall():
self._q.put((row_id, user_id, session_id, json.loads(msgs_json)))
def _get_conn(self) -> sqlite3.Connection:
"""Return a cached connection for the current thread."""
conn = getattr(self._local, "conn", None)
if conn is None:
- conn = sqlite3.connect(
- str(self._db_path), timeout=30, check_same_thread=False
- )
+ conn = sqlite3.connect(str(self._db_path), timeout=30, check_same_thread=False)
conn.row_factory = sqlite3.Row
self._local.conn = conn
with self._connections_lock:
self._connections.add(conn)
return conn
+ def _execute(self, sql: str, params: tuple = ()) -> sqlite3.Cursor:
+ """Execute + commit on this thread's connection."""
+ cur = self._get_conn().execute(sql, params)
+ cur.connection.commit()
+ return cur
+
def _close_thread_conn(self) -> None:
conn = getattr(self._local, "conn", None)
if conn is None:
@@ -394,77 +278,38 @@ class _WriteQueue:
self._local.conn = None
with self._connections_lock:
self._connections.discard(conn)
- try:
+ with suppress(Exception):
conn.close()
- except Exception:
- pass
-
- def _close_all_connections(self) -> None:
- """Close tracked connections left by short-lived worker threads."""
- with self._connections_lock:
- connections = list(self._connections)
- self._connections.clear()
- for conn in connections:
- try:
- conn.close()
- except Exception:
- pass
-
- def _init_db(self) -> None:
- conn = self._get_conn()
- conn.execute("""CREATE TABLE IF NOT EXISTS pending (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- user_id TEXT, session_id TEXT, messages_json TEXT,
- created_at TEXT, last_error TEXT
- )""")
- conn.commit()
-
- def _pending_rows(self) -> list:
- conn = self._get_conn()
- return conn.execute("SELECT id, user_id, session_id, messages_json FROM pending ORDER BY id ASC LIMIT 200").fetchall()
def enqueue(self, user_id: str, session_id: str, messages: list) -> None:
now = datetime.now(timezone.utc).isoformat()
with self._shutdown_lock:
if self._shutdown:
return
- conn = self._get_conn()
- cur = conn.execute(
+ cur = self._execute(
"INSERT INTO pending (user_id, session_id, messages_json, created_at) VALUES (?,?,?,?)",
(user_id, session_id, json.dumps(messages, ensure_ascii=False), now),
)
- row_id = cur.lastrowid
- conn.commit()
- self._q.put((row_id, user_id, session_id, messages))
+ self._q.put((cur.lastrowid, user_id, session_id, messages))
def _flush_row(self, row_id: int, user_id: str, session_id: str, messages: list) -> None:
try:
self._client.ingest_session(user_id, session_id, messages)
- conn = self._get_conn()
- conn.execute("DELETE FROM pending WHERE id = ?", (row_id,))
- conn.commit()
+ self._execute("DELETE FROM pending WHERE id = ?", (row_id,))
except Exception as exc:
logger.warning("RetainDB ingest failed (will retry): %s", exc)
- conn = self._get_conn()
- conn.execute("UPDATE pending SET last_error = ? WHERE id = ?", (str(exc), row_id))
- conn.commit()
+ self._execute("UPDATE pending SET last_error = ? WHERE id = ?", (str(exc), row_id))
time.sleep(2)
def _loop(self) -> None:
try:
- while True:
+ while (item := self._q.get()) is not _ASYNC_SHUTDOWN:
try:
- item = self._q.get(timeout=5)
- if item is _ASYNC_SHUTDOWN:
- break
self._flush_row(*item)
- except queue.Empty:
- continue
except Exception as exc:
logger.error("RetainDB writer error: %s", exc)
finally:
- # sqlite3 connections must close on their owning thread.
- self._close_thread_conn()
+ self._close_thread_conn() # sqlite3 connections must close on their owning thread
def shutdown(self) -> None:
with self._shutdown_lock:
@@ -472,57 +317,60 @@ class _WriteQueue:
return
self._shutdown = True
self._q.put(_ASYNC_SHUTDOWN)
- # Caller thread owns connection opened by _init_db/_pending_rows.
- self._close_thread_conn()
+ self._close_thread_conn() # caller thread owns the connection opened in __init__
self._thread.join(timeout=10)
if not self._thread.is_alive():
- # MemoryManager's executor may have opened a connection on a
- # worker that has already exited; check_same_thread=False lets
- # shutdown close that tracked handle deterministically.
- self._close_all_connections()
+ # Executor workers that already exited may have left tracked handles;
+ # check_same_thread=False lets shutdown close them deterministically.
+ with self._connections_lock:
+ connections, self._connections = list(self._connections), set()
+ for conn in connections:
+ with suppress(Exception):
+ conn.close()
-# ---------------------------------------------------------------------------
-# Overlay formatter
-# ---------------------------------------------------------------------------
+# ── Overlay formatter ────────────────────────────────────────────────────────
-def _build_overlay(profile: dict, query_result: dict, local_entries: list[str] | None = None) -> str:
- def _compact(s: str) -> str:
- return re.sub(r"\s+", " ", str(s or "")).strip()[:320]
-
- def _norm(s: str) -> str:
- return re.sub(r"[^a-z0-9 ]", "", _compact(s).lower())
-
- seen: list[str] = [_norm(e) for e in (local_entries or []) if _norm(e)]
- profile_items: list[str] = []
- for m in list((profile or {}).get("memories") or [])[:5]:
- c = _compact((m or {}).get("content") or "")
- n = _norm(c)
- if c and n not in seen:
- seen.append(n)
- profile_items.append(c)
-
- query_items: list[str] = []
- for r in list((query_result or {}).get("results") or [])[:5]:
- c = _compact((r or {}).get("content") or "")
- n = _norm(c)
- if c and n not in seen:
- seen.append(n)
- query_items.append(c)
+def _compact(s: str) -> str:
+ return re.sub(r"\s+", " ", str(s or "")).strip()[:320]
+
+def _norm(s: str) -> str:
+ return re.sub(r"[^a-z0-9 ]", "", _compact(s).lower())
+
+
+def _build_overlay(profile: dict, query_result: dict, local_entries: list[str] | None = None) -> str:
+ """Profile + query memories (5 each, compacted, deduped against each other and *local_entries*)."""
+ seen = {_norm(e) for e in (local_entries or []) if _norm(e)}
+
+ def _dedupe(items) -> list[str]:
+ out: list[str] = []
+ for m in list(items or [])[:5]:
+ c = _compact((m or {}).get("content") or "")
+ if c and _norm(c) not in seen:
+ seen.add(_norm(c))
+ out.append(c)
+ return out
+
+ profile_items = _dedupe((profile or {}).get("memories"))
+ query_items = _dedupe((query_result or {}).get("results"))
if not profile_items and not query_items:
return ""
+ return "\n".join(
+ ["[RetainDB Context]", "Profile:"] + ([f"- {i}" for i in profile_items] or ["- None"])
+ + ["Relevant memories:"] + ([f"- {i}" for i in query_items] or ["- None"])
+ )
+
- lines = ["[RetainDB Context]", "Profile:"]
- lines += [f"- {i}" for i in profile_items] or ["- None"]
- lines.append("Relevant memories:")
- lines += [f"- {i}" for i in query_items] or ["- None"]
- return "\n".join(lines)
+# ── Provider ─────────────────────────────────────────────────────────────────
+# Agent self-model keys -> prefetch line formatter, in display order.
+_AGENT_MODEL_FIELDS = (
+ ("persona", lambda v: f"Persona: {v}"),
+ ("persistent_instructions", lambda v: "Instructions:\n" + "\n".join(f"- {i}" for i in v)),
+ ("working_style", lambda v: f"Working style: {v}"),
+)
-# ---------------------------------------------------------------------------
-# Main plugin class
-# ---------------------------------------------------------------------------
class RetainDBMemoryProvider(MemoryProvider):
"""RetainDB cloud memory — durable queue, semantic search, dialectic synthesis, shared files."""
@@ -530,21 +378,13 @@ class RetainDBMemoryProvider(MemoryProvider):
def __init__(self):
self._client: _Client | None = None
self._queue: _WriteQueue | None = None
- self._user_id = "default"
- self._session_id = ""
- self._agent_id = "hermes"
+ self._user_id, self._session_id, self._agent_id = "default", "", "hermes"
self._lock = threading.Lock()
-
- # Prefetch caches
- self._context_result = ""
- self._dialectic_result = ""
+ # Prefetch caches + thread tracking (prevents accumulation on rapid calls)
+ self._context_result = self._dialectic_result = ""
self._agent_model: dict = {}
-
- # Prefetch thread tracking — prevents accumulation on rapid calls
self._prefetch_threads: list[threading.Thread] = []
- # ── Core identity ──────────────────────────────────────────────────────
-
@property
def name(self) -> str:
return "retaindb"
@@ -559,51 +399,29 @@ class RetainDBMemoryProvider(MemoryProvider):
{"key": "project", "description": "Project identifier (optional — uses 'default' project if not set)", "default": ""},
]
- # ── Lifecycle ──────────────────────────────────────────────────────────
-
def initialize(self, session_id: str, **kwargs) -> None:
- # Non-secret fields fall back to config.yaml (written by the Dashboard)
- # when the env var is unset: env -> config.yaml -> default.
+ # Non-secret fields resolve env -> config.yaml (written by the Dashboard) -> default.
provider_config = _load_retaindb_config()
- api_key = get_secret("RETAINDB_API_KEY", "") or ""
- base_url_raw = (
- os.environ.get("RETAINDB_BASE_URL")
- or _config_str(provider_config.get("base_url"))
- or _DEFAULT_BASE_URL
- )
- base_url = re.sub(r"/+$", "", base_url_raw)
-
- # Project resolution: RETAINDB_PROJECT > config.yaml project > hermes-<profile> > "default"
- # If unset, the API auto-creates and uses the "default" project — no config required.
- explicit = os.environ.get("RETAINDB_PROJECT") or _config_str(provider_config.get("project"))
- if explicit:
- project = explicit
- else:
- hermes_home = str(kwargs.get("hermes_home", ""))
- profile_name = os.path.basename(hermes_home) if hermes_home else ""
- project = f"hermes-{profile_name}" if (profile_name and profile_name not in {"", ".hermes"}) else "default"
-
- self._client = _Client(api_key, base_url, project)
+ base_url = re.sub(r"/+$", "", os.environ.get("RETAINDB_BASE_URL") or _config_str(provider_config.get("base_url")) or _DEFAULT_BASE_URL)
+ # Project: RETAINDB_PROJECT > config.yaml > hermes-<profile> > "default" (API auto-creates "default").
+ project = os.environ.get("RETAINDB_PROJECT") or _config_str(provider_config.get("project"))
+ if not project:
+ profile_name = os.path.basename(str(kwargs.get("hermes_home", "")))
+ project = f"hermes-{profile_name}" if profile_name not in {"", ".hermes"} else "default"
+
+ self._client = _Client(get_secret("RETAINDB_API_KEY", "") or "", base_url, project)
self._session_id = session_id
self._user_id = kwargs.get("user_id", "default") or "default"
self._agent_id = kwargs.get("agent_id", "hermes") or "hermes"
from hermes_constants import get_hermes_home
hermes_home_path = get_hermes_home()
- db_path = hermes_home_path / "retaindb_queue.db"
- self._queue = _WriteQueue(self._client, db_path)
-
+ self._queue = _WriteQueue(self._client, hermes_home_path / "retaindb_queue.db")
# Seed agent identity from SOUL.md in background
soul_path = hermes_home_path / "SOUL.md"
- if soul_path.exists():
- soul_content = soul_path.read_text(encoding="utf-8", errors="replace").strip()
- if soul_content:
- threading.Thread(
- target=self._seed_soul,
- args=(soul_content,),
- name="retaindb-soul-seed",
- daemon=True,
- ).start()
+ soul_content = soul_path.read_text(encoding="utf-8", errors="replace").strip() if soul_path.exists() else ""
+ if soul_content:
+ threading.Thread(target=self._seed_soul, args=(soul_content,), name="retaindb-soul-seed", daemon=True).start()
def _seed_soul(self, content: str) -> None:
try:
@@ -614,125 +432,88 @@ class RetainDBMemoryProvider(MemoryProvider):
def system_prompt_block(self) -> str:
project = self._client.project if self._client else "retaindb"
return (
- "# RetainDB Memory\n"
- f"Active. Project: {project}.\n"
+ f"# RetainDB Memory\nActive. Project: {project}.\n"
"Use retaindb_search to find memories, retaindb_remember to store facts, "
"retaindb_profile for a user overview, retaindb_context for current-task context."
)
- # ── Background prefetch (fires at turn-end, consumed next turn-start) ──
+ # Background prefetch (fires at turn-end, consumed next turn-start)
def queue_prefetch(self, query: str, *, session_id: str = "") -> None:
"""Fire context + dialectic + agent model prefetches in background."""
if not self._client:
return
- # Wait for any still-running prefetch threads before spawning new ones.
- # Prevents thread accumulation if turns fire faster than prefetches complete.
+ # Wait for the previous batch so threads don't accumulate on rapid turns.
for t in self._prefetch_threads:
t.join(timeout=2.0)
if any(t.is_alive() for t in self._prefetch_threads):
logger.debug("RetainDB prefetch still running; skipping new batch")
return
- threads = [
- threading.Thread(target=self._prefetch_context, args=(query,), name="retaindb-ctx", daemon=True),
- threading.Thread(target=self._prefetch_dialectic, args=(query,), name="retaindb-dialectic", daemon=True),
- threading.Thread(target=self._prefetch_agent_model, name="retaindb-agent-model", daemon=True),
- ]
+ jobs = (
+ ("retaindb-ctx", "context", lambda: ("_context_result", self._context_overlay(query)["context"])),
+ ("retaindb-dialectic", "dialectic", lambda: self._fetch_dialectic(query)),
+ ("retaindb-agent-model", "agent model", self._fetch_agent_model),
+ )
+ threads = [threading.Thread(target=self._store, args=(label, fetch), name=name, daemon=True) for name, label, fetch in jobs]
self._prefetch_threads = threads
for t in threads:
t.start()
- def _prefetch_context(self, query: str) -> None:
- try:
- query_result = self._client.query_context(self._user_id, self._session_id, query)
- profile = self._client.get_profile(self._user_id)
- overlay = _build_overlay(profile, query_result)
- with self._lock:
- self._context_result = overlay
- except Exception as exc:
- logger.debug("RetainDB context prefetch failed: %s", exc)
+ def _context_overlay(self, query: str) -> dict:
+ query_result = self._client.query_context(self._user_id, self._session_id, query)
+ profile = self._client.get_profile(self._user_id)
+ return {"context": _build_overlay(profile, query_result), "raw": query_result}
- def _prefetch_dialectic(self, query: str) -> None:
- try:
- result = self._client.ask_user(self._user_id, query, reasoning_level=self._reasoning_level(query))
- answer = str(result.get("answer") or "")
- if answer:
- with self._lock:
- self._dialectic_result = answer
- except Exception as exc:
- logger.debug("RetainDB dialectic prefetch failed: %s", exc)
+ def _fetch_dialectic(self, query: str) -> tuple[str, str | None]:
+ result = self._client.ask_user(self._user_id, query, reasoning_level=self._reasoning_level(query))
+ return "_dialectic_result", str(result.get("answer") or "") or None
+
+ def _fetch_agent_model(self) -> tuple[str, dict | None]:
+ model = self._client.get_agent_model(self._agent_id)
+ return "_agent_model", model if model.get("memory_count", 0) > 0 else None
- def _prefetch_agent_model(self) -> None:
+ def _store(self, label: str, fetch: Callable[[], tuple[str, Any]]) -> None:
+ """Run one prefetch job; store (attr, value) under the lock unless value is None; log failures at debug."""
try:
- model = self._client.get_agent_model(self._agent_id)
- if model.get("memory_count", 0) > 0:
+ attr, value = fetch()
+ if value is not None:
with self._lock:
- self._agent_model = model
+ setattr(self, attr, value)
except Exception as exc:
- logger.debug("RetainDB agent model prefetch failed: %s", exc)
+ logger.debug("RetainDB %s prefetch failed: %s", label, exc)
@staticmethod
def _reasoning_level(query: str) -> str:
n = len(query)
- if n < 120:
- return "low"
- if n < 400:
- return "medium"
- return "high"
+ return "low" if n < 120 else "medium" if n < 400 else "high"
def prefetch(self, query: str, *, session_id: str = "") -> str:
"""Consume prefetched results and return them as a context block."""
with self._lock:
- context = self._context_result
- dialectic = self._dialectic_result
- agent_model = self._agent_model
- self._context_result = ""
- self._dialectic_result = ""
+ context, dialectic, agent_model = self._context_result, self._dialectic_result, self._agent_model
+ self._context_result = self._dialectic_result = ""
self._agent_model = {}
-
- parts: list[str] = []
- if context:
- parts.append(context)
+ parts = [context] if context else []
if dialectic:
parts.append(f"[RetainDB User Synthesis]\n{dialectic}")
- if agent_model and agent_model.get("memory_count", 0) > 0:
- model_lines: list[str] = []
- if agent_model.get("persona"):
- model_lines.append(f"Persona: {agent_model['persona']}")
- if agent_model.get("persistent_instructions"):
- model_lines.append("Instructions:\n" + "\n".join(f"- {i}" for i in agent_model["persistent_instructions"]))
- if agent_model.get("working_style"):
- model_lines.append(f"Working style: {agent_model['working_style']}")
+ if agent_model.get("memory_count", 0) > 0:
+ model_lines = [fmt(agent_model[k]) for k, fmt in _AGENT_MODEL_FIELDS if agent_model.get(k)]
if model_lines:
parts.append("[RetainDB Agent Self-Model]\n" + "\n".join(model_lines))
-
return "\n\n".join(parts)
- # ── Turn sync ──────────────────────────────────────────────────────────
-
def sync_turn(self, user_content: str, assistant_content: str, *, session_id: str = "") -> None:
"""Queue turn for async ingest. Returns immediately."""
if not self._queue or not user_content:
return
now = datetime.now(timezone.utc).isoformat()
- self._queue.enqueue(
- self._user_id,
- session_id or self._session_id,
- [
- {"role": "user", "content": user_content, "timestamp": now},
- {"role": "assistant", "content": assistant_content, "timestamp": now},
- ],
- )
-
- # ── Tools ──────────────────────────────────────────────────────────────
+ self._queue.enqueue(self._user_id, session_id or self._session_id, [
+ {"role": "user", "content": user_content, "timestamp": now},
+ {"role": "assistant", "content": assistant_content, "timestamp": now},
+ ])
def get_tool_schemas(self) -> List[Dict[str, Any]]:
- return [
- PROFILE_SCHEMA, SEARCH_SCHEMA, CONTEXT_SCHEMA,
- REMEMBER_SCHEMA, FORGET_SCHEMA,
- FILE_UPLOAD_SCHEMA, FILE_LIST_SCHEMA, FILE_READ_SCHEMA,
- FILE_INGEST_SCHEMA, FILE_DELETE_SCHEMA,
- ]
+ return list(_SCHEMAS)
def handle_tool_call(self, tool_name: str, args: dict, **kwargs) -> str:
if not self._client:
@@ -743,96 +524,43 @@ class RetainDBMemoryProvider(MemoryProvider):
return tool_error(str(exc))
def _dispatch(self, tool_name: str, args: dict) -> Any:
- c = self._client
-
- if tool_name == "retaindb_profile":
- return c.get_profile(self._user_id)
-
- if tool_name == "retaindb_search":
- query = args.get("query", "")
- if not query:
- return {"error": "query is required"}
- return c.search(self._user_id, self._session_id, query, top_k=min(int(args.get("top_k", 8)), 20))
-
- if tool_name == "retaindb_context":
- query = args.get("query", "")
- if not query:
- return {"error": "query is required"}
- query_result = c.query_context(self._user_id, self._session_id, query)
- profile = c.get_profile(self._user_id)
- overlay = _build_overlay(profile, query_result)
- return {"context": overlay, "raw": query_result}
-
- if tool_name == "retaindb_remember":
- content = args.get("content", "")
- if not content:
- return {"error": "content is required"}
- return c.add_memory(
- self._user_id, self._session_id, content,
- memory_type=args.get("memory_type", "factual"),
- importance=float(args.get("importance", 0.7)),
- )
-
- if tool_name == "retaindb_forget":
- memory_id = args.get("memory_id", "")
- if not memory_id:
- return {"error": "memory_id is required"}
- return c.delete_memory(memory_id)
-
- # ── File tools ──────────────────────────────────────────────────────
-
- if tool_name == "retaindb_upload_file":
- local_path = args.get("local_path", "")
- if not local_path:
- return {"error": "local_path is required"}
- path_obj = Path(local_path)
- if not path_obj.exists():
- return {"error": f"File not found: {local_path}"}
- try:
- raise_if_read_blocked(str(path_obj))
- except ValueError as exc:
- return {"error": str(exc)}
- data = path_obj.read_bytes()
- import mimetypes
- mime = mimetypes.guess_type(path_obj.name)[0] or "application/octet-stream"
- remote_path = args.get("remote_path") or f"/{path_obj.name}"
- result = c.upload_file(data, path_obj.name, remote_path, mime, args.get("scope", "PROJECT"), None)
- if args.get("ingest") and result.get("file", {}).get("id"):
- ingest = c.ingest_file(result["file"]["id"], user_id=self._user_id, agent_id=self._agent_id)
- result["ingest"] = ingest
- return result
-
- if tool_name == "retaindb_list_files":
- return c.list_files(prefix=args.get("prefix"), limit=int(args.get("limit", 50)))
-
- if tool_name == "retaindb_read_file":
- file_id = args.get("file_id", "")
- if not file_id:
- return {"error": "file_id is required"}
- meta = c.get_file(file_id)
- file_info = meta.get("file") or {}
- mime = (file_info.get("mime_type") or "").lower()
- raw = c.read_file_content(file_id)
- if not (mime.startswith("text/") or any(file_info.get("name", "").endswith(e) for e in (".txt", ".md", ".json", ".csv", ".yaml", ".yml", ".xml", ".html"))):
- return {"file_id": file_id, "rdb_uri": file_info.get("rdb_uri"), "name": file_info.get("name"), "content": None, "note": "Binary file — use retaindb_ingest_file to extract text into memory."}
- text = raw.decode("utf-8", errors="replace")
- return {"file_id": file_id, "rdb_uri": file_info.get("rdb_uri"), "name": file_info.get("name"), "content": text[:32000], "truncated": len(text) > 32000}
-
- if tool_name == "retaindb_ingest_file":
- file_id = args.get("file_id", "")
- if not file_id:
- return {"error": "file_id is required"}
- return c.ingest_file(file_id, user_id=self._user_id, agent_id=self._agent_id)
-
- if tool_name == "retaindb_delete_file":
- file_id = args.get("file_id", "")
- if not file_id:
- return {"error": "file_id is required"}
- return c.delete_file(file_id)
-
- return {"error": f"Unknown tool: {tool_name}"}
-
- # ── Optional hooks ─────────────────────────────────────────────────────
+ entry = _TOOLS.get(tool_name)
+ if entry is None:
+ return {"error": f"Unknown tool: {tool_name}"}
+ required, handler = entry
+ value = args.get(required, "") if required else None
+ if required and not value:
+ return {"error": f"{required} is required"}
+ return handler(self, args, value)
+
+ def _tool_upload_file(self, args: dict, local_path: str) -> Any:
+ path_obj = Path(local_path)
+ if not path_obj.exists():
+ return {"error": f"File not found: {local_path}"}
+ try:
+ raise_if_read_blocked(str(path_obj))
+ except ValueError as exc:
+ return {"error": str(exc)}
+ import mimetypes
+ mime = mimetypes.guess_type(path_obj.name)[0] or "application/octet-stream"
+ result = self._client.upload_file(path_obj.read_bytes(), path_obj.name, args.get("remote_path") or f"/{path_obj.name}",
+ mime, args.get("scope", "PROJECT"), None)
+ if args.get("ingest") and result.get("file", {}).get("id"):
+ result["ingest"] = self._ingest(result["file"]["id"])
+ return result
+
+ def _tool_read_file(self, args: dict, file_id: str) -> Any:
+ file_info = self._client.get_file(file_id).get("file") or {}
+ mime = (file_info.get("mime_type") or "").lower()
+ raw = self._client.read_file_content(file_id)
+ out = {"file_id": file_id, "rdb_uri": file_info.get("rdb_uri"), "name": file_info.get("name")}
+ if not (mime.startswith("text/") or file_info.get("name", "").endswith(_TEXT_EXTS)):
+ return {**out, "content": None, "note": "Binary file — use retaindb_ingest_file to extract text into memory."}
+ text = raw.decode("utf-8", errors="replace")
+ return {**out, "content": text[:32000], "truncated": len(text) > 32000}
+
+ def _ingest(self, file_id: str) -> Any:
+ return self._client.ingest_file(file_id, user_id=self._user_id, agent_id=self._agent_id)
def on_memory_write(self, action: str, target: str, content: str) -> None:
"""Mirror built-in memory writes to RetainDB."""
@@ -848,11 +576,25 @@ class RetainDBMemoryProvider(MemoryProvider):
for t in self._prefetch_threads:
t.join(timeout=3.0)
self._prefetch_threads = []
- queue_obj = self._queue
- self._queue = None
+ queue_obj, self._queue, self._client = self._queue, None, None
if queue_obj:
queue_obj.shutdown()
- self._client = None
+
+
+# tool name -> (required arg or None, handler(provider, args, required_value)); missing arg -> "<arg> is required"
+_TOOLS: Dict[str, tuple[str | None, Callable[..., Any]]] = {
+ "retaindb_profile": (None, lambda p, a, _: p._client.get_profile(p._user_id)),
+ "retaindb_search": ("query", lambda p, a, q: p._client.search(p._user_id, p._session_id, q, top_k=min(int(a.get("top_k", 8)), 20))),
+ "retaindb_context": ("query", lambda p, a, q: p._context_overlay(q)),
+ "retaindb_remember": ("content", lambda p, a, c: p._client.add_memory(
+ p._user_id, p._session_id, c, memory_type=a.get("memory_type", "factual"), importance=float(a.get("importance", 0.7)))),
+ "retaindb_forget": ("memory_id", lambda p, a, m: p._client.delete_memory(m)),
+ "retaindb_upload_file": ("local_path", RetainDBMemoryProvider._tool_upload_file),
+ "retaindb_list_files": (None, lambda p, a, _: p._client.list_files(prefix=a.get("prefix"), limit=int(a.get("limit", 50)))),
+ "retaindb_read_file": ("file_id", RetainDBMemoryProvider._tool_read_file),
+ "retaindb_ingest_file": ("file_id", lambda p, a, f: p._ingest(f)),
+ "retaindb_delete_file": ("file_id", lambda p, a, f: p._client.delete_file(f)),
+}
def register(ctx) -> None:
diff --git a/plugins/memory/supermemory/__init__.py b/plugins/memory/supermemory/__init__.py
index 5bd968bd61c..6b25511d8d1 100644
--- a/plugins/memory/supermemory/__init__.py
+++ b/plugins/memory/supermemory/__init__.py
@@ -1,8 +1,5 @@
-"""Supermemory memory plugin using the MemoryProvider interface.
-
-Provides semantic long-term memory with profile recall, semantic search,
-explicit memory tools, cleaned turn capture, and session-end conversation ingest.
-"""
+"""Supermemory memory plugin (MemoryProvider): profile recall, semantic search, explicit memory tools,
+cleaned turn capture, and session-end conversation ingest."""
from __future__ import annotations
@@ -11,11 +8,10 @@ import logging
import os
import re
import threading
-import urllib.error
import urllib.request
from datetime import datetime, timezone
from pathlib import Path
-from typing import Any, Dict, List, Optional
+from typing import Any, Callable, Dict, List, Optional
from agent.memory_provider import MemoryProvider
from agent.secret_scope import get_secret, is_multiplex_active
@@ -30,19 +26,12 @@ _DEFAULT_CAPTURE_MODE = "all"
_DEFAULT_SEARCH_MODE = "hybrid"
_VALID_SEARCH_MODES = ("hybrid", "memories", "documents")
_DEFAULT_API_TIMEOUT = 5.0
-_MIN_CAPTURE_LENGTH = 10
_MAX_ENTITY_CONTEXT_LENGTH = 1500
_DEFAULT_BASE_URL = "https://api.supermemory.ai"
_API_KEY_URL = "http://app.supermemory.ai/integrations?connect=hermes"
-_TRIVIAL_RE = re.compile(
- r"^(ok|okay|thanks|thank you|got it|sure|yes|no|yep|nope|k|ty|thx|np)\.?$",
- re.IGNORECASE,
-)
-_CONTEXT_STRIP_RE = re.compile(
- r"<supermemory-context>[\s\S]*?</supermemory-context>\s*", re.DOTALL
-)
-_CONTAINERS_STRIP_RE = re.compile(
- r"<supermemory-containers>[\s\S]*?</supermemory-containers>\s*", re.DOTALL
+# Strips injected <supermemory-context> / <supermemory-containers> blocks before capture.
+_INJECTED_BLOCK_RE = re.compile(
+ r"<supermemory-(context|containers)>[\s\S]*?</supermemory-\1>\s*", re.DOTALL
)
_DEFAULT_ENTITY_CONTEXT = (
"User-assistant conversation. Format: [role: user]...[user:end] and "
@@ -53,134 +42,117 @@ _DEFAULT_ENTITY_CONTEXT = (
"Do not remember temporary intents, one-time tasks, assistant actions, implementation details, or in-progress status.\n\n"
"When in doubt, store less."
)
+# snake_case tool name -> kebab-case alias exposed alongside it.
+_KEBAB_ALIASES = {
+ "supermemory_store": "supermemory-save",
+ "supermemory_search": "supermemory-search",
+ "supermemory_forget": "supermemory-forget",
+ "supermemory_profile": "supermemory-profile",
+}
+_ALIAS_TO_TOOL = {kebab: snake for snake, kebab in _KEBAB_ALIASES.items()}
def _default_config() -> dict:
- return {
- "container_tag": _DEFAULT_CONTAINER_TAG,
- "auto_recall": True,
- "auto_capture": True,
- "max_recall_results": _DEFAULT_MAX_RECALL_RESULTS,
- "profile_frequency": _DEFAULT_PROFILE_FREQUENCY,
- "capture_mode": _DEFAULT_CAPTURE_MODE,
- "search_mode": _DEFAULT_SEARCH_MODE,
- "entity_context": _DEFAULT_ENTITY_CONTEXT,
- "api_timeout": _DEFAULT_API_TIMEOUT,
- "base_url": "",
- "enable_custom_container_tags": False,
- "custom_containers": [],
- "custom_container_instructions": "",
- }
+ """Fresh copy of every config default (lists are copied so callers can mutate safely)."""
+ return {k: (list(d) if isinstance(d, list) else d) for k, (d, _) in _CONFIG_SPEC.items()}
def _sanitize_tag(raw: str) -> str:
- tag = re.sub(r"[^a-zA-Z0-9_]", "_", raw or "")
- tag = re.sub(r"_+", "_", tag)
- return tag.strip("_") or _DEFAULT_CONTAINER_TAG
+ return re.sub(r"_+", "_", re.sub(r"[^a-zA-Z0-9_]", "_", raw or "")).strip("_") or _DEFAULT_CONTAINER_TAG
def _resolve_base_url(config_value: Any = "") -> str:
- """Resolve the API base URL: config > SUPERMEMORY_BASE_URL env var > default.
-
- Supports self-hosted Supermemory servers (e.g. http://localhost:6767).
- """
- raw = (
- str(config_value or "").strip()
- or os.environ.get("SUPERMEMORY_BASE_URL", "").strip()
- )
+ """Resolve the API base URL: config > SUPERMEMORY_BASE_URL env var > default (self-hosted support)."""
+ raw = str(config_value or "").strip() or os.environ.get("SUPERMEMORY_BASE_URL", "").strip()
return (raw or _DEFAULT_BASE_URL).rstrip("/") or _DEFAULT_BASE_URL
def _clamp_entity_context(text: str) -> str:
- if not text:
- return _DEFAULT_ENTITY_CONTEXT
- text = text.strip()
- return text[:_MAX_ENTITY_CONTEXT_LENGTH]
+ return text.strip()[:_MAX_ENTITY_CONTEXT_LENGTH] if text else _DEFAULT_ENTITY_CONTEXT
+
+
+_BOOL_WORDS = {**dict.fromkeys(("true", "1", "yes", "y", "on"), True), **dict.fromkeys(("false", "0", "no", "n", "off"), False)}
def _as_bool(value: Any, default: bool) -> bool:
+ """bool passthrough; common true/false words parsed; anything else (incl. ints) -> default."""
if isinstance(value, bool):
return value
- if isinstance(value, str):
- lowered = value.strip().lower()
- if lowered in {"true", "1", "yes", "y", "on"}:
- return True
- if lowered in {"false", "0", "no", "n", "off"}:
- return False
- return default
+ return _BOOL_WORDS.get(value.strip().lower(), default) if isinstance(value, str) else default
-def _load_supermemory_config(hermes_home: str) -> dict:
- config = _default_config()
- config_path = Path(hermes_home) / "supermemory.json"
- if config_path.exists():
+def _valid_search_mode(mode: str) -> str:
+ return mode if mode in _VALID_SEARCH_MODES else _DEFAULT_SEARCH_MODE
+
+
+def _clamp_number(value: Any, default, lo, hi, cast):
+ """Cast ``value`` and clamp it to [lo, hi]; fall back to ``default`` on any conversion error."""
+ try:
+ return max(lo, min(hi, cast(value)))
+ except Exception:
+ return default
+
+
+# config key -> (default, normalizer applied to the raw/merged value). Order = supermemory.json layout.
+# container_tag is kept raw here: {identity} templates are resolved in initialize(), and
+# _sanitize_tag runs AFTER that resolution. custom_containers, by contrast, are sanitized on load.
+_CONFIG_SPEC: Dict[str, tuple] = {
+ "container_tag": (_DEFAULT_CONTAINER_TAG, lambda v: str(v).strip() or _DEFAULT_CONTAINER_TAG),
+ "auto_recall": (True, lambda v: _as_bool(v, True)),
+ "auto_capture": (True, lambda v: _as_bool(v, True)),
+ "max_recall_results": (_DEFAULT_MAX_RECALL_RESULTS, lambda v: _clamp_number(v, _DEFAULT_MAX_RECALL_RESULTS, 1, 20, int)),
+ "profile_frequency": (_DEFAULT_PROFILE_FREQUENCY, lambda v: _clamp_number(v, _DEFAULT_PROFILE_FREQUENCY, 1, 500, int)),
+ "capture_mode": (_DEFAULT_CAPTURE_MODE, lambda v: "everything" if v == "everything" else "all"),
+ "search_mode": (_DEFAULT_SEARCH_MODE, lambda v: _valid_search_mode(str(v).strip().lower())),
+ "entity_context": (_DEFAULT_ENTITY_CONTEXT, lambda v: _clamp_entity_context(str(v))),
+ "api_timeout": (_DEFAULT_API_TIMEOUT, lambda v: _clamp_number(v, _DEFAULT_API_TIMEOUT, 0.5, 15.0, float)),
+ "base_url": ("", lambda v: str(v or "").strip()),
+ # Multi-container support
+ "enable_custom_container_tags": (False, lambda v: _as_bool(v, False)),
+ "custom_containers": ([], lambda v: [_sanitize_tag(str(t)) for t in v if t] if isinstance(v, list) else []),
+ "custom_container_instructions": ("", lambda v: str(v).strip()),
+}
+
+
+def _read_json_dict(path: Path) -> dict:
+ """Return the JSON object stored at ``path`` or {} if missing/invalid."""
+ if path.exists():
try:
- raw = json.loads(config_path.read_text(encoding="utf-8"))
+ raw = json.loads(path.read_text(encoding="utf-8"))
if isinstance(raw, dict):
- config.update({k: v for k, v in raw.items() if v is not None})
+ return raw
except Exception:
- logger.debug("Failed to parse %s", config_path, exc_info=True)
-
- # Keep raw container_tag — template variables like {identity} are resolved
- # in initialize(), and _sanitize_tag runs AFTER resolution.
- raw_tag = str(config.get("container_tag", _DEFAULT_CONTAINER_TAG)).strip()
- config["container_tag"] = raw_tag if raw_tag else _DEFAULT_CONTAINER_TAG
- config["auto_recall"] = _as_bool(config.get("auto_recall"), True)
- config["auto_capture"] = _as_bool(config.get("auto_capture"), True)
- try:
- config["max_recall_results"] = max(1, min(20, int(config.get("max_recall_results", _DEFAULT_MAX_RECALL_RESULTS))))
- except Exception:
- config["max_recall_results"] = _DEFAULT_MAX_RECALL_RESULTS
- try:
- config["profile_frequency"] = max(1, min(500, int(config.get("profile_frequency", _DEFAULT_PROFILE_FREQUENCY))))
- except Exception:
- config["profile_frequency"] = _DEFAULT_PROFILE_FREQUENCY
- config["capture_mode"] = "everything" if config.get("capture_mode") == "everything" else "all"
- raw_search_mode = str(config.get("search_mode", _DEFAULT_SEARCH_MODE)).strip().lower()
- config["search_mode"] = raw_search_mode if raw_search_mode in _VALID_SEARCH_MODES else _DEFAULT_SEARCH_MODE
- config["entity_context"] = _clamp_entity_context(str(config.get("entity_context", _DEFAULT_ENTITY_CONTEXT)))
- try:
- config["api_timeout"] = max(0.5, min(15.0, float(config.get("api_timeout", _DEFAULT_API_TIMEOUT))))
- except Exception:
- config["api_timeout"] = _DEFAULT_API_TIMEOUT
- config["base_url"] = str(config.get("base_url", "") or "").strip()
+ logger.debug("Failed to parse %s", path, exc_info=True)
+ return {}
- # Multi-container support
- config["enable_custom_container_tags"] = _as_bool(config.get("enable_custom_container_tags"), False)
- raw_containers = config.get("custom_containers", [])
- if isinstance(raw_containers, list):
- config["custom_containers"] = [_sanitize_tag(str(t)) for t in raw_containers if t]
- else:
- config["custom_containers"] = []
- config["custom_container_instructions"] = str(config.get("custom_container_instructions", "")).strip()
+def _load_supermemory_config(hermes_home: str) -> dict:
+ config = _default_config()
+ config.update({k: v for k, v in _read_json_dict(Path(hermes_home) / "supermemory.json").items() if v is not None})
+ for key, (_, normalize) in _CONFIG_SPEC.items():
+ config[key] = normalize(config[key])
return config
def _save_supermemory_config(values: dict, hermes_home: str) -> None:
config_path = Path(hermes_home) / "supermemory.json"
- existing = {}
- if config_path.exists():
- try:
- raw = json.loads(config_path.read_text(encoding="utf-8"))
- if isinstance(raw, dict):
- existing = raw
- except Exception:
- existing = {}
+ existing = _read_json_dict(config_path)
existing.update(values)
from utils import atomic_json_write
atomic_json_write(config_path, existing, mode=0o600, sort_keys=True)
+# Ordered: first matching pattern wins.
+_CATEGORY_PATTERNS = (
+ ("preference", r"prefer|like|love|hate|want"),
+ ("decision", r"decided|will use|going with"),
+ ("fact", r"\bis\b|\bare\b|\bhas\b|\bhave\b"),
+)
+
+
def _detect_category(text: str) -> str:
lowered = text.lower()
- if re.search(r"prefer|like|love|hate|want", lowered):
- return "preference"
- if re.search(r"decided|will use|going with", lowered):
- return "decision"
- if re.search(r"\bis\b|\bare\b|\bhas\b|\bhave\b", lowered):
- return "fact"
- return "other"
+ return next((cat for cat, pat in _CATEGORY_PATTERNS if re.search(pat, lowered)), "other")
def _format_relative_time(iso_timestamp: str) -> str:
@@ -190,141 +162,109 @@ def _format_relative_time(iso_timestamp: str) -> str:
seconds = (now - dt).total_seconds()
if seconds < 1800:
return "just now"
- if seconds < 3600:
- return f"{int(seconds / 60)}m ago"
- if seconds < 86400:
- return f"{int(seconds / 3600)}h ago"
- if seconds < 604800:
- return f"{int(seconds / 86400)}d ago"
- if dt.year == now.year:
- return dt.strftime("%d %b")
- return dt.strftime("%d %b %Y")
+ for limit, unit, label in ((3600, 60, "m"), (86400, 3600, "h"), (604800, 86400, "d")):
+ if seconds < limit:
+ return f"{int(seconds / unit)}{label} ago"
+ return dt.strftime("%d %b" if dt.year == now.year else "%d %b %Y")
except Exception:
return ""
def _deduplicate_recall(static_facts: list, dynamic_facts: list, search_results: list) -> tuple[list, list, list]:
- seen = set()
- out_static, out_dynamic, out_search = [], [], []
- for fact in static_facts or []:
- if fact and fact not in seen:
- seen.add(fact)
- out_static.append(fact)
- for fact in dynamic_facts or []:
- if fact and fact not in seen:
- seen.add(fact)
- out_dynamic.append(fact)
- for item in search_results or []:
- memory = item.get("memory", "")
- if memory and memory not in seen:
- seen.add(memory)
- out_search.append(item)
- return out_static, out_dynamic, out_search
+ """Drop empties and repeats across the three lists; earlier lists win (profile facts beat search hits)."""
+ seen: set = set()
+ def _unique(items, key=lambda x: x):
+ out = []
+ for item in items or []:
+ k = key(item)
+ if k and k not in seen:
+ seen.add(k)
+ out.append(item)
+ return out
+
+ return _unique(static_facts), _unique(dynamic_facts), _unique(search_results, key=lambda i: i.get("memory", ""))
+
+
+def _bullets(title: str, items: list) -> str:
+ return f"## {title}\n" + "\n".join(f"- {item}" for item in items)
-def _format_prefetch_context(static_facts: list, dynamic_facts: list, search_results: list, max_results: int) -> str:
- statics, dynamics, search = _deduplicate_recall(static_facts, dynamic_facts, search_results)
- statics = statics[:max_results]
- dynamics = dynamics[:max_results]
- search = search[:max_results]
- if not statics and not dynamics and not search:
- return ""
- sections = []
- if statics:
- sections.append("## User Profile (Persistent)\n" + "\n".join(f"- {item}" for item in statics))
- if dynamics:
- sections.append("## Recent Context\n" + "\n".join(f"- {item}" for item in dynamics))
- if search:
- lines = []
- for item in search:
- memory = item.get("memory", "")
- if not memory:
- continue
- similarity = item.get("similarity")
- updated = item.get("updated_at") or item.get("updatedAt") or ""
- prefix_bits = []
- rel = _format_relative_time(updated)
- if rel:
- prefix_bits.append(f"[{rel}]")
- if similarity is not None:
- try:
- prefix_bits.append(f"[{round(float(similarity) * 100)}%]")
- except Exception:
- pass
- prefix = " ".join(prefix_bits)
- lines.append(f"- {prefix} {memory}".strip())
- if lines:
- sections.append("## Relevant Memories\n" + "\n".join(lines))
+def _similarity_pct(value: Any) -> Optional[int]:
+ """0..1 similarity -> whole percent; None when absent or unparseable."""
+ if value is None:
+ return None
+ try:
+ return round(float(value) * 100)
+ except Exception:
+ return None
+
+
+def _profile_sections(static_facts: list, dynamic_facts: list) -> list[str]:
+ return ([_bullets("User Profile (Persistent)", static_facts)] if static_facts else []) + \
+ ([_bullets("Recent Context", dynamic_facts)] if dynamic_facts else [])
+
+
+def _format_prefetch_context(static_facts: list, dynamic_facts: list, search_results: list, max_results: int) -> str:
+ statics, dynamics, search = (lst[:max_results] for lst in _deduplicate_recall(static_facts, dynamic_facts, search_results))
+ sections = _profile_sections(statics, dynamics)
+ lines = []
+ for item in search: # dedupe already dropped items without a memory string
+ rel = _format_relative_time(item.get("updated_at") or item.get("updatedAt") or "")
+ pct = _similarity_pct(item.get("similarity"))
+ prefix_bits = ([f"[{rel}]"] if rel else []) + ([f"[{pct}%]"] if pct is not None else [])
+ lines.append(f"- {' '.join(prefix_bits)} {item['memory']}".strip())
+ if lines:
+ sections.append("## Relevant Memories\n" + "\n".join(lines))
if not sections:
return ""
-
- intro = (
- "The following is background context from long-term memory. Use it silently when relevant. "
- "Do not force memories into the conversation."
- )
- body = "\n\n".join(sections)
- return f"<supermemory-context>\n{intro}\n\n{body}\n</supermemory-context>"
+ intro = ("The following is background context from long-term memory. Use it silently when relevant. "
+ "Do not force memories into the conversation.")
+ return f"<supermemory-context>\n{intro}\n\n" + "\n\n".join(sections) + "\n</supermemory-context>"
def _clean_text_for_capture(text: str) -> str:
- text = _CONTEXT_STRIP_RE.sub("", text or "")
- text = _CONTAINERS_STRIP_RE.sub("", text)
- return text.strip()
+ return _INJECTED_BLOCK_RE.sub("", text or "").strip()
-def _is_trivial_message(text: str) -> bool:
- return bool(_TRIVIAL_RE.match((text or "").strip()))
+def _updated_at(item: Any) -> Any:
+ return getattr(item, "updated_at", None) or getattr(item, "updatedAt", None)
class _SupermemoryClient:
def __init__(self, api_key: str, timeout: float, container_tag: str,
search_mode: str = "hybrid", base_url: str = ""):
- # Lazy-install the supermemory SDK on demand. ensure() honors
- # security.allow_lazy_installs (default true) and, on a sealed Docker
- # venv, redirects the install to the durable target. On failure we
- # fall through so the raw import below produces the canonical
- # ImportError message.
+ # Lazy-install the SDK on demand (honors security.allow_lazy_installs and
+ # sealed Docker venvs). On failure fall through so the raw import below
+ # produces the canonical ImportError message.
try:
from tools.lazy_deps import ensure as _lazy_ensure
_lazy_ensure("memory.supermemory", prompt=False)
- except ImportError:
- pass
except Exception:
pass
from supermemory import Supermemory
self._api_key = api_key
self._container_tag = container_tag
- self._search_mode = search_mode if search_mode in _VALID_SEARCH_MODES else _DEFAULT_SEARCH_MODE
+ self._search_mode = _valid_search_mode(search_mode)
self._timeout = timeout
self._base_url = _resolve_base_url(base_url)
- self._client = Supermemory(
- api_key=api_key,
- base_url=self._base_url,
- timeout=timeout,
- max_retries=0,
- default_headers={"x-sm-source": "hermes"},
- )
+ self._client = Supermemory(api_key=api_key, base_url=self._base_url, timeout=timeout, max_retries=0,
+ default_headers={"x-sm-source": "hermes"})
def _merge_metadata(self, metadata: Optional[dict]) -> dict:
# sm_source routes Hermes writes into the "Hermes" Space in the Supermemory
- # app so the user can filter / bulk-manage them per source agent. This is a
- # functional routing key for the user, not vendor telemetry.
+ # app so the user can filter / bulk-manage them per source agent (a
+ # functional routing key for the user, not vendor telemetry).
merged = {"sm_source": "hermes", **(metadata or {})}
legacy_source = merged.pop("source", None)
if legacy_source and "type" not in merged:
merged["type"] = str(legacy_source)
return merged
- def add_memory(self, content: str, metadata: Optional[dict] = None, *,
- entity_context: str = "", container_tag: Optional[str] = None,
- custom_id: Optional[str] = None) -> dict:
- tag = container_tag or self._container_tag
- kwargs: dict[str, Any] = {
- "content": content.strip(),
- "container_tags": [tag],
- }
+ def add_memory(self, content: str, metadata: Optional[dict] = None, *, entity_context: str = "",
+ container_tag: Optional[str] = None, custom_id: Optional[str] = None) -> dict:
+ kwargs: dict[str, Any] = {"content": content.strip(), "container_tags": [container_tag or self._container_tag]}
if metadata:
kwargs["metadata"] = self._merge_metadata(metadata)
if entity_context:
@@ -334,107 +274,86 @@ class _SupermemoryClient:
result = self._client.documents.add(**kwargs)
return {"id": getattr(result, "id", "")}
- def search_memories(self, query: str, *, limit: int = 5,
- container_tag: Optional[str] = None,
+ def search_memories(self, query: str, *, limit: int = 5, container_tag: Optional[str] = None,
search_mode: Optional[str] = None) -> list[dict]:
- tag = container_tag or self._container_tag
mode = search_mode or self._search_mode
- kwargs: dict[str, Any] = {"q": query, "container_tag": tag, "limit": limit}
+ kwargs: dict[str, Any] = {"q": query, "container_tag": container_tag or self._container_tag, "limit": limit}
if mode in _VALID_SEARCH_MODES:
kwargs["search_mode"] = mode
response = self._client.search.memories(**kwargs)
- results = []
- for item in (getattr(response, "results", None) or []):
- results.append({
+ return [
+ {
"id": getattr(item, "id", ""),
"memory": getattr(item, "memory", "") or "",
"similarity": getattr(item, "similarity", None),
- "updated_at": getattr(item, "updated_at", None) or getattr(item, "updatedAt", None),
+ "updated_at": _updated_at(item),
"metadata": getattr(item, "metadata", None),
- })
- return results
+ }
+ for item in (getattr(response, "results", None) or [])
+ ]
- def get_profile(self, query: Optional[str] = None, *,
- container_tag: Optional[str] = None) -> dict:
- tag = container_tag or self._container_tag
- kwargs: dict[str, Any] = {"container_tag": tag}
+ def get_profile(self, query: Optional[str] = None, *, container_tag: Optional[str] = None) -> dict:
+ kwargs: dict[str, Any] = {"container_tag": container_tag or self._container_tag}
if query:
kwargs["q"] = query
response = self._client.profile(**kwargs)
profile_data = getattr(response, "profile", None)
search_data = getattr(response, "search_results", None) or getattr(response, "searchResults", None)
- static = getattr(profile_data, "static", []) or [] if profile_data else []
- dynamic = getattr(profile_data, "dynamic", []) or [] if profile_data else []
raw_results = getattr(search_data, "results", None) or search_data or []
- search_results = []
- if isinstance(raw_results, list):
- for item in raw_results:
- if isinstance(item, dict):
- search_results.append(item)
- else:
- search_results.append({
- "memory": getattr(item, "memory", ""),
- "updated_at": getattr(item, "updated_at", None) or getattr(item, "updatedAt", None),
- "similarity": getattr(item, "similarity", None),
- })
- return {"static": static, "dynamic": dynamic, "search_results": search_results}
+ return {
+ "static": (getattr(profile_data, "static", []) or []) if profile_data else [],
+ "dynamic": (getattr(profile_data, "dynamic", []) or []) if profile_data else [],
+ "search_results": [
+ item if isinstance(item, dict) else {
+ "memory": getattr(item, "memory", ""),
+ "updated_at": _updated_at(item),
+ "similarity": getattr(item, "similarity", None),
+ }
+ for item in raw_results
+ ] if isinstance(raw_results, list) else [],
+ }
def forget_memory(self, memory_id: str, *, container_tag: Optional[str] = None) -> None:
- tag = container_tag or self._container_tag
- self._client.memories.forget(container_tag=tag, id=memory_id)
+ self._client.memories.forget(container_tag=container_tag or self._container_tag, id=memory_id)
def forget_by_query(self, query: str, *, container_tag: Optional[str] = None) -> dict:
results = self.search_memories(query, limit=5, container_tag=container_tag)
if not results:
return {"success": False, "message": "No matching memory found to forget."}
- target = results[0]
- memory_id = target.get("id", "")
+ memory_id = results[0].get("id", "")
if not memory_id:
return {"success": False, "message": "Best matching memory has no id."}
self.forget_memory(memory_id, container_tag=container_tag)
- preview = (target.get("memory") or "")[:100]
- return {"success": True, "message": f'Forgot: "{preview}"', "id": memory_id}
+ return {"success": True, "message": f'Forgot: "{(results[0].get("memory") or "")[:100]}"', "id": memory_id}
def ingest_conversation(self, session_id: str, messages: list[dict], metadata: dict | None = None) -> None:
- payload: dict = {
- "conversationId": session_id,
- "messages": messages,
- "containerTags": [self._container_tag],
- }
+ payload: dict = {"conversationId": session_id, "messages": messages, "containerTags": [self._container_tag]}
if metadata:
payload["metadata"] = self._merge_metadata(metadata)
req = urllib.request.Request(
f"{self._base_url}/v4/conversations",
data=json.dumps(payload).encode("utf-8"),
- headers={
- "Authorization": f"Bearer {self._api_key}",
- "Content-Type": "application/json",
- "x-sm-source": "hermes",
- },
+ headers={"Authorization": f"Bearer {self._api_key}", "Content-Type": "application/json",
+ "x-sm-source": "hermes"},
method="POST",
)
with urllib.request.urlopen(req, timeout=self._timeout + 3):
return
-def _resolve_container_tag_for_setup(hermes_home: str, *, identity: str = "default") -> str:
- config = _load_supermemory_config(hermes_home)
- env_tag = os.environ.get("SUPERMEMORY_CONTAINER_TAG", "").strip()
- raw_tag = env_tag or config["container_tag"]
+def _resolve_container_tag(config_tag: str, identity: str) -> str:
+ """SUPERMEMORY_CONTAINER_TAG env > config > default; {identity} expands to the agent identity, then sanitize."""
+ raw_tag = os.environ.get("SUPERMEMORY_CONTAINER_TAG", "").strip() or config_tag
return _sanitize_tag(raw_tag.replace("{identity}", identity))
def _probe_supermemory_connection(api_key: str, hermes_home: str, *, identity: str = "default") -> dict:
config = _load_supermemory_config(hermes_home)
- base_url = _resolve_base_url(config["base_url"])
status = {
- "ok": False,
- "error": "",
- "container_tag": _resolve_container_tag_for_setup(hermes_home, identity=identity),
- "profile_facts": 0,
- "auto_recall": bool(config["auto_recall"]),
- "auto_capture": bool(config["auto_capture"]),
+ "ok": False, "error": "", "profile_facts": 0,
+ "container_tag": _resolve_container_tag(config["container_tag"], identity),
+ "auto_recall": bool(config["auto_recall"]), "auto_capture": bool(config["auto_capture"]),
}
if not (api_key or "").strip():
status["error"] = "SUPERMEMORY_API_KEY not set"
@@ -445,19 +364,13 @@ def _probe_supermemory_connection(api_key: str, hermes_home: str, *, identity: s
status["error"] = "supermemory package not installed"
return status
try:
- client = _SupermemoryClient(
- api_key=api_key.strip(),
- timeout=config["api_timeout"],
- container_tag=status["container_tag"],
- search_mode=config["search_mode"],
- base_url=base_url,
- )
+ client = _SupermemoryClient(api_key=api_key.strip(), timeout=config["api_timeout"],
+ container_tag=status["container_tag"], search_mode=config["search_mode"],
+ base_url=_resolve_base_url(config["base_url"]))
profile = client.get_profile()
- facts = [
- fact for fact in (profile.get("static") or []) + (profile.get("dynamic") or [])
- if fact and str(fact).strip()
- ]
- status["profile_facts"] = len(facts)
+ status["profile_facts"] = sum(
+ 1 for f in (profile.get("static") or []) + (profile.get("dynamic") or []) if f and str(f).strip()
+ )
status["ok"] = True
except Exception as exc:
status["error"] = str(exc).strip()[:160] or "connection failed"
@@ -465,120 +378,92 @@ def _probe_supermemory_connection(api_key: str, hermes_home: str, *, identity: s
def _format_connection_summary(status: dict) -> str:
- recall = "on" if status.get("auto_recall") else "off"
- capture = "on" if status.get("auto_capture") else "off"
container = status.get("container_tag") or _DEFAULT_CONTAINER_TAG
+ flags = (f"auto_recall {'on' if status.get('auto_recall') else 'off'} · "
+ f"auto_capture {'on' if status.get('auto_capture') else 'off'}")
if status.get("ok"):
facts = int(status.get("profile_facts") or 0)
- fact_label = "fact" if facts == 1 else "facts"
- return (
- f"✓ Connected · container: {container} · {facts} profile {fact_label} · "
- f"auto_recall {recall} · auto_capture {capture}"
- )
- err = status.get("error") or "connection failed"
- return f"✗ {err} · container: {container} · auto_recall {recall} · auto_capture {capture}"
-
-
-STORE_SCHEMA = {
- "name": "supermemory_store",
- "description": "Store an explicit memory for future recall.",
- "parameters": {
- "type": "object",
- "properties": {
- "content": {"type": "string", "description": "The memory content to store."},
- "metadata": {"type": "object", "description": "Optional metadata attached to the memory."},
- },
- "required": ["content"],
- },
-}
+ return f"✓ Connected · container: {container} · {facts} profile {'fact' if facts == 1 else 'facts'} · {flags}"
+ return f"✗ {status.get('error') or 'connection failed'} · container: {container} · {flags}"
-SEARCH_SCHEMA = {
- "name": "supermemory_search",
- "description": "Search long-term memory by semantic similarity.",
- "parameters": {
- "type": "object",
- "properties": {
- "query": {"type": "string", "description": "What to search for."},
- "limit": {"type": "integer", "description": "Maximum results to return, 1 to 20."},
- },
- "required": ["query"],
- },
-}
-FORGET_SCHEMA = {
- "name": "supermemory_forget",
- "description": "Forget a memory by exact id or by best-match query.",
- "parameters": {
- "type": "object",
- "properties": {
- "id": {"type": "string", "description": "Exact memory id to delete."},
- "query": {"type": "string", "description": "Query used to find the memory to forget."},
- },
- },
-}
+def _schema(name: str, description: str, properties: dict, required: Optional[list] = None) -> dict:
+ parameters: dict[str, Any] = {"type": "object", "properties": properties}
+ if required:
+ parameters["required"] = required
+ return {"name": name, "description": description, "parameters": parameters}
-PROFILE_SCHEMA = {
- "name": "supermemory_profile",
- "description": "Retrieve persistent profile facts and recent memory context.",
- "parameters": {
- "type": "object",
- "properties": {
- "query": {"type": "string", "description": "Optional query to focus the profile response."},
- },
- },
-}
+
+def _str_prop(description: str) -> dict:
+ return {"type": "string", "description": description}
+
+
+STORE_SCHEMA, SEARCH_SCHEMA, FORGET_SCHEMA, PROFILE_SCHEMA = _BASE_SCHEMAS = [
+ _schema("supermemory_store", "Store an explicit memory for future recall.", {
+ "content": _str_prop("The memory content to store."),
+ "metadata": {"type": "object", "description": "Optional metadata attached to the memory."},
+ }, required=["content"]),
+ _schema("supermemory_search", "Search long-term memory by semantic similarity.", {
+ "query": _str_prop("What to search for."),
+ "limit": {"type": "integer", "description": "Maximum results to return, 1 to 20."},
+ }, required=["query"]),
+ _schema("supermemory_forget", "Forget a memory by exact id or by best-match query.", {
+ "id": _str_prop("Exact memory id to delete."),
+ "query": _str_prop("Query used to find the memory to forget."),
+ }),
+ _schema("supermemory_profile", "Retrieve persistent profile facts and recent memory context.", {
+ "query": _str_prop("Optional query to focus the profile response."),
+ }),
+]
+
+
+def _turns_to_messages(turns: List[Dict[str, str]]) -> list[dict]:
+ return [{"role": role, "content": turn[role]} for turn in turns for role in ("user", "assistant") if turn.get(role)]
class SupermemoryMemoryProvider(MemoryProvider):
def __init__(self):
- self._config = _default_config()
- self._api_key = ""
+ self._api_key = self._session_id = self._hermes_home = self._prefetch_result = ""
self._client: Optional[_SupermemoryClient] = None
self._container_tag = _DEFAULT_CONTAINER_TAG
- self._session_id = ""
self._turn_count = 0
- self._prefetch_result = ""
self._prefetch_lock = threading.Lock()
self._prefetch_thread: Optional[threading.Thread] = None
self._sync_thread: Optional[threading.Thread] = None
self._write_thread: Optional[threading.Thread] = None
- self._auto_recall = True
- self._auto_capture = True
- self._max_recall_results = _DEFAULT_MAX_RECALL_RESULTS
- self._profile_frequency = _DEFAULT_PROFILE_FREQUENCY
- self._capture_mode = _DEFAULT_CAPTURE_MODE
- self._search_mode = _DEFAULT_SEARCH_MODE
- self._entity_context = _DEFAULT_ENTITY_CONTEXT
- self._api_timeout = _DEFAULT_API_TIMEOUT
- self._base_url = _DEFAULT_BASE_URL
- self._hermes_home = ""
self._write_enabled = True
self._active = False
- # Multi-container support
- self._enable_custom_containers = False
- self._custom_containers: List[str] = []
- self._custom_container_instructions = ""
- self._allowed_containers: List[str] = []
self._session_turns: List[Dict[str, str]] = []
+ self._apply_config(_default_config())
+ self._base_url = _DEFAULT_BASE_URL # env var is only consulted in initialize()
+ self._allowed_containers = []
+
+ def _apply_config(self, config: dict) -> None:
+ self._config = config
+ for key in ("auto_recall", "auto_capture", "max_recall_results", "profile_frequency", "capture_mode",
+ "search_mode", "entity_context", "api_timeout"):
+ setattr(self, f"_{key}", config[key])
+ # Base URL: config > SUPERMEMORY_BASE_URL env var > api.supermemory.ai (self-hosted support).
+ self._base_url = _resolve_base_url(config["base_url"])
+ # Multi-container support
+ self._enable_custom_containers = config["enable_custom_container_tags"]
+ self._custom_containers: List[str] = config["custom_containers"]
+ self._custom_container_instructions = config["custom_container_instructions"]
+ self._allowed_containers: List[str] = [self._container_tag] + list(self._custom_containers)
@property
def name(self) -> str:
return "supermemory"
def is_available(self) -> bool:
- # Key presence only — no SDK import check. The supermemory SDK is
- # lazy-installed when the client is first constructed in initialize()
- # (see _SupermemoryClient.__init__). Gating availability on the SDK
- # being importable here would be a chicken-and-egg trap: on a sealed
- # Docker venv the package isn't present until ensure() runs, but
- # ensure() only runs once the provider is loaded — which this gates.
- # Mirrors honcho/mem0, which check config only. No network calls.
+ # Key presence only, no SDK import check: the SDK is lazy-installed when the
+ # client is first constructed in initialize(), so gating on importability here
+ # would be a chicken-and-egg trap on sealed venvs. Mirrors honcho/mem0.
return bool(get_secret("SUPERMEMORY_API_KEY", ""))
def get_config_schema(self):
- # Only prompt for the API key during `hermes memory setup`.
- # All other options are documented for $HERMES_HOME/supermemory.json
- # or the SUPERMEMORY_CONTAINER_TAG env var.
+ # Only prompt for the API key during `hermes memory setup`; other options
+ # live in $HERMES_HOME/supermemory.json or SUPERMEMORY_CONTAINER_TAG.
return [
{"key": "api_key", "description": "Supermemory API key", "secret": True, "required": True, "env_var": "SUPERMEMORY_API_KEY", "url": _API_KEY_URL},
]
@@ -595,27 +480,21 @@ class SupermemoryMemoryProvider(MemoryProvider):
from hermes_constants import get_hermes_home
del provider_config
- hermes_home = str(get_hermes_home())
api_key = get_secret("SUPERMEMORY_API_KEY", "") or ""
- status = _probe_supermemory_connection(api_key, hermes_home)
+ status = _probe_supermemory_connection(api_key, str(get_hermes_home()))
return {"summary": _format_connection_summary(status)}
def post_setup(self, hermes_home: str, config: dict) -> None:
from hermes_cli.config import save_config
from hermes_cli.memory_setup import _prompt, _write_env_vars
- print("\n Configuring supermemory:\n")
- print(f" Get your API key at {_API_KEY_URL}\n")
+ print(f"\n Configuring supermemory:\n\n Get your API key at {_API_KEY_URL}\n")
- env_writes: dict[str, str] = {}
existing = os.environ.get("SUPERMEMORY_API_KEY", "")
- if existing:
- masked = f"...{existing[-4:]}" if len(existing) > 4 else "set"
- val = _prompt(f"Supermemory API key (current: {masked}, blank to keep)", secret=True)
- else:
- val = _prompt("Supermemory API key", secret=True)
- if val:
- env_writes["SUPERMEMORY_API_KEY"] = val
+ masked = f"...{existing[-4:]}" if len(existing) > 4 else "set"
+ val = _prompt(f"Supermemory API key (current: {masked}, blank to keep)" if existing else "Supermemory API key",
+ secret=True)
+ env_writes = {"SUPERMEMORY_API_KEY": val} if val else {}
if not isinstance(config.get("memory"), dict):
config["memory"] = {}
@@ -625,25 +504,15 @@ class SupermemoryMemoryProvider(MemoryProvider):
if env_writes:
_write_env_vars(env_writes, hermes_home=hermes_home)
- api_key = env_writes.get("SUPERMEMORY_API_KEY") or existing
- # Make the freshly-entered key visible to the connection probe below.
- # (Checks the VALUE of SUPERMEMORY_API_KEY, not whether the key string
- # happens to name some unrelated env var.)
- # Single-profile convenience only: never write a profile's key into
- # the process-global environ under a multiplexed gateway — sibling
- # profiles' turns (and any subprocess spawned with env=os.environ)
- # would inherit it.
- if (
- api_key
- and not is_multiplex_active()
- and os.environ.get("SUPERMEMORY_API_KEY") != api_key
- ):
+ api_key = val or existing
+ # Make the freshly-entered key visible to the probe below. Single-profile
+ # only: under a multiplexed gateway, writing to the process-global environ
+ # would leak the key to sibling profiles and their subprocesses.
+ if api_key and not is_multiplex_active() and os.environ.get("SUPERMEMORY_API_KEY") != api_key:
os.environ["SUPERMEMORY_API_KEY"] = api_key
status = _probe_supermemory_connection(api_key, hermes_home)
- print(f"\n {_format_connection_summary(status)}")
- print("\n Memory provider: supermemory")
- print(" Activation saved to config.yaml")
+ print(f"\n {_format_connection_summary(status)}\n\n Memory provider: supermemory\n Activation saved to config.yaml")
if env_writes:
print(" API keys saved to .env")
print("\n Start a new session to activate.\n")
@@ -653,47 +522,21 @@ class SupermemoryMemoryProvider(MemoryProvider):
self._hermes_home = kwargs.get("hermes_home") or str(get_hermes_home())
self._session_id = session_id
self._turn_count = 0
- self._config = _load_supermemory_config(self._hermes_home)
+ config = _load_supermemory_config(self._hermes_home)
self._api_key = get_secret("SUPERMEMORY_API_KEY", "") or ""
- # Resolve container tag: env var > config > default.
- # Supports {identity} template for profile-scoped containers.
- env_tag = os.environ.get("SUPERMEMORY_CONTAINER_TAG", "").strip()
- raw_tag = env_tag or self._config["container_tag"]
- identity = kwargs.get("agent_identity", "default")
- self._container_tag = _sanitize_tag(raw_tag.replace("{identity}", identity))
-
- self._auto_recall = self._config["auto_recall"]
- self._auto_capture = self._config["auto_capture"]
- self._max_recall_results = self._config["max_recall_results"]
- self._profile_frequency = self._config["profile_frequency"]
- self._capture_mode = self._config["capture_mode"]
- self._search_mode = self._config["search_mode"]
- self._entity_context = self._config["entity_context"]
- self._api_timeout = self._config["api_timeout"]
- # Base URL: config > SUPERMEMORY_BASE_URL env var > api.supermemory.ai.
- # Supports self-hosted Supermemory servers.
- self._base_url = _resolve_base_url(self._config["base_url"])
- self._enable_custom_containers = self._config["enable_custom_container_tags"]
- self._custom_containers = self._config["custom_containers"]
- self._custom_container_instructions = self._config["custom_container_instructions"]
- self._allowed_containers = [self._container_tag] + list(self._custom_containers)
-
+ self._container_tag = _resolve_container_tag(config["container_tag"], kwargs.get("agent_identity", "default"))
+ self._apply_config(config)
self._session_turns = []
- agent_context = kwargs.get("agent_context", "")
- self._write_enabled = agent_context not in {"cron", "flush", "subagent"}
+ self._write_enabled = kwargs.get("agent_context", "") not in {"cron", "flush", "subagent"}
self._active = bool(self._api_key)
self._client = None
if self._active:
try:
- self._client = _SupermemoryClient(
- api_key=self._api_key,
- timeout=self._api_timeout,
- container_tag=self._container_tag,
- search_mode=self._search_mode,
- base_url=self._base_url,
- )
+ self._client = _SupermemoryClient(api_key=self._api_key, timeout=self._api_timeout,
+ container_tag=self._container_tag, search_mode=self._search_mode,
+ base_url=self._base_url)
except Exception:
logger.warning("Supermemory initialization failed", exc_info=True)
self._active = False
@@ -711,8 +554,7 @@ class SupermemoryMemoryProvider(MemoryProvider):
"Use supermemory-search, supermemory-save, supermemory-forget, and supermemory-profile (aliases: supermemory_search, supermemory_store, supermemory_forget, supermemory_profile).",
]
if self._enable_custom_containers and self._custom_containers:
- tags_str = ", ".join(self._allowed_containers)
- lines.append(f"\nMulti-container mode enabled. Available containers: {tags_str}.")
+ lines.append(f"\nMulti-container mode enabled. Available containers: {', '.join(self._allowed_containers)}.")
lines.append("Pass an optional container_tag to supermemory_search, supermemory_store, supermemory_forget, and supermemory_profile to target a specific container.")
if self._custom_container_instructions:
lines.append(f"\n{self._custom_container_instructions}")
@@ -724,13 +566,12 @@ class SupermemoryMemoryProvider(MemoryProvider):
try:
profile = self._client.get_profile(query=query[:200])
include_profile = self._turn_count <= 1 or (self._turn_count % self._profile_frequency == 0)
- context = _format_prefetch_context(
+ return _format_prefetch_context(
static_facts=profile["static"] if include_profile else [],
dynamic_facts=profile["dynamic"] if include_profile else [],
search_results=profile["search_results"],
max_results=self._max_recall_results,
)
- return context
except Exception:
logger.debug("Supermemory prefetch failed", exc_info=True)
return ""
@@ -738,56 +579,43 @@ class SupermemoryMemoryProvider(MemoryProvider):
def sync_turn(self, user_content: str, assistant_content: str, *, session_id: str = "") -> None:
if not self._active or not self._auto_capture or not self._write_enabled or not self._client:
return
-
clean_user = _clean_text_for_capture(user_content)
clean_assistant = _clean_text_for_capture(assistant_content)
- if not clean_user and not clean_assistant:
- return
-
- # Buffer every turn for the single full-session document written at end/switch/shutdown
- self._session_turns.append({"user": clean_user, "assistant": clean_assistant})
+ if clean_user or clean_assistant:
+ # Buffer every turn for the single full-session document written at end/switch/shutdown
+ self._session_turns.append({"user": clean_user, "assistant": clean_assistant})
- def on_session_end(self, messages: List[Dict[str, Any]]) -> None:
- if not self._active or not self._write_enabled or not self._client or not self._session_id:
- return
- cleaned = []
- for message in messages or []:
- role = message.get("role")
- if role not in {"user", "assistant"}:
- continue
- content = _clean_text_for_capture(str(message.get("content", "")))
- if content:
- cleaned.append({"role": role, "content": content})
- if not cleaned:
- return
- if len(cleaned) == 1 and len(cleaned[0].get("content", "")) < 20:
- return
+ def _ingest_session(self, session_id: str, messages: list[dict], metadata: dict,
+ fail_msg: str, level: int = logging.DEBUG) -> None:
try:
self._client.ingest_conversation(
- self._session_id,
- cleaned,
- metadata={
- "type": "full_session",
- "session_id": self._session_id,
- "message_count": len(cleaned),
- },
+ session_id, messages, metadata={"type": "full_session", "session_id": session_id, **metadata}
)
- except urllib.error.HTTPError:
- logger.warning("Supermemory session ingest failed", exc_info=True)
except Exception:
- logger.warning("Supermemory session ingest failed", exc_info=True)
+ logger.log(level, fail_msg, exc_info=True)
+ def _ingest_buffered_turns(self, session_id: str, *, partial: bool, fail_msg: str) -> None:
+ # message_count reports 2 per buffered turn regardless of empty sides.
+ self._ingest_session(session_id, _turns_to_messages(self._session_turns),
+ {"message_count": len(self._session_turns) * 2, "partial": partial}, fail_msg)
+
+ def on_session_end(self, messages: List[Dict[str, Any]]) -> None:
+ if not self._active or not self._write_enabled or not self._client or not self._session_id:
+ return
+ cleaned = [
+ {"role": m.get("role"), "content": _clean_text_for_capture(str(m.get("content", "")))}
+ for m in messages or [] if m.get("role") in {"user", "assistant"}
+ ]
+ cleaned = [m for m in cleaned if m["content"]]
+ if not cleaned or (len(cleaned) == 1 and len(cleaned[0]["content"]) < 20):
+ return
+ self._ingest_session(self._session_id, cleaned, {"message_count": len(cleaned)},
+ "Supermemory session ingest failed", level=logging.WARNING)
# Clear buffer so shutdown() doesn't duplicate on normal exit
self._session_turns = []
- def on_session_switch(
- self,
- new_session_id: str,
- *,
- parent_session_id: str = "",
- reset: bool = False,
- **kwargs,
- ) -> None:
+ def on_session_switch(self, new_session_id: str, *, parent_session_id: str = "", reset: bool = False,
+ **kwargs) -> None:
"""Flush any buffered turns from the old session as one document, then reset for the new session."""
if not self._active or not self._write_enabled or not self._client:
self._session_id = str(new_session_id or "").strip() or self._session_id
@@ -795,32 +623,10 @@ class SupermemoryMemoryProvider(MemoryProvider):
return
old_session_id = self._session_id
- old_turns = list(self._session_turns)
-
- # Flush previous session via conversations ingest (with metadata)
- if old_turns and old_session_id:
- messages: list[dict] = []
- for turn in old_turns:
- if turn.get("user"):
- messages.append({"role": "user", "content": turn["user"]})
- if turn.get("assistant"):
- messages.append({"role": "assistant", "content": turn["assistant"]})
-
- try:
- self._client.ingest_conversation(
- old_session_id,
- messages,
- metadata={
- "type": "full_session",
- "session_id": old_session_id,
- "message_count": len(old_turns) * 2,
- "partial": not reset,
- },
- )
- except Exception:
- logger.debug("Supermemory session-switch ingest failed", exc_info=True)
+ if self._session_turns and old_session_id:
+ self._ingest_buffered_turns(old_session_id, partial=not reset,
+ fail_msg="Supermemory session-switch ingest failed")
- # Reset for new session
self._session_id = str(new_session_id or "").strip() or old_session_id
self._session_turns = []
self._turn_count = 0
@@ -833,17 +639,13 @@ class SupermemoryMemoryProvider(MemoryProvider):
def _run():
try:
- self._client.add_memory(
- content.strip(),
- metadata={"target": target, "type": "explicit_memory"},
- entity_context=self._entity_context,
- )
+ self._client.add_memory(content.strip(), metadata={"target": target, "type": "explicit_memory"},
+ entity_context=self._entity_context)
except Exception:
logger.debug("Supermemory on_memory_write failed", exc_info=True)
if self._write_thread and self._write_thread.is_alive():
self._write_thread.join(timeout=2.0)
- self._write_thread = None
self._write_thread = threading.Thread(target=_run, daemon=False, name="supermemory-memory-write")
self._write_thread.start()
@@ -851,27 +653,7 @@ class SupermemoryMemoryProvider(MemoryProvider):
# Emergency fallback (crashes only). Buffer is cleared on normal on_session_end().
if self._active and self._write_enabled and self._client and self._session_turns and self._session_id:
logger.warning("Supermemory: Saving session via shutdown (session=%s, turns=%d)", self._session_id, len(self._session_turns))
-
- messages: list[dict] = []
- for turn in self._session_turns:
- if turn.get("user"):
- messages.append({"role": "user", "content": turn["user"]})
- if turn.get("assistant"):
- messages.append({"role": "assistant", "content": turn["assistant"]})
-
- try:
- self._client.ingest_conversation(
- self._session_id,
- messages,
- metadata={
- "type": "full_session",
- "session_id": self._session_id,
- "message_count": len(self._session_turns) * 2,
- "partial": True,
- },
- )
- except Exception:
- logger.debug("Supermemory shutdown ingest failed", exc_info=True)
+ self._ingest_buffered_turns(self._session_id, partial=True, fail_msg="Supermemory shutdown ingest failed")
for attr_name in ("_prefetch_thread", "_sync_thread", "_write_thread"):
thread = getattr(self, attr_name, None)
@@ -880,171 +662,108 @@ class SupermemoryMemoryProvider(MemoryProvider):
setattr(self, attr_name, None)
def _resolve_tool_container_tag(self, args: dict) -> Optional[str]:
- """Validate and resolve container_tag from tool call args.
-
- Returns None (use primary) if multi-container is disabled or no tag provided.
- Returns the validated tag if it's in the allowed list.
- Raises ValueError if the tag is not whitelisted.
- """
- if not self._enable_custom_containers:
- return None
- tag = str(args.get("container_tag") or "").strip()
+ """Return the validated container_tag from args, None for primary; raise ValueError if not whitelisted."""
+ tag = str(args.get("container_tag") or "").strip() if self._enable_custom_containers else ""
if not tag:
return None
sanitized = _sanitize_tag(tag)
if sanitized not in self._allowed_containers:
- raise ValueError(
- f"Container tag '{sanitized}' is not allowed. "
- f"Allowed: {', '.join(self._allowed_containers)}"
- )
+ raise ValueError(f"Container tag '{sanitized}' is not allowed. Allowed: {', '.join(self._allowed_containers)}")
return sanitized
def get_tool_schemas(self) -> List[Dict[str, Any]]:
- def with_kebab_aliases(schemas: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
- aliases = {
- "supermemory_store": "supermemory-save",
- "supermemory_search": "supermemory-search",
- "supermemory_forget": "supermemory-forget",
- "supermemory_profile": "supermemory-profile",
- }
- expanded = list(schemas)
- for schema in schemas:
- kebab = aliases.get(schema.get("name", ""))
- if not kebab:
- continue
- copy = json.loads(json.dumps(schema))
- copy["name"] = kebab
- expanded.append(copy)
- return expanded
-
- if not self._enable_custom_containers:
- return with_kebab_aliases([STORE_SCHEMA, SEARCH_SCHEMA, FORGET_SCHEMA, PROFILE_SCHEMA])
-
- # When multi-container is enabled, add optional container_tag to relevant tools
- container_param = {
- "type": "string",
- "description": f"Optional container tag. Allowed: {', '.join(self._allowed_containers)}. Defaults to primary ({self._container_tag}).",
- }
- schemas = []
- for base in [STORE_SCHEMA, SEARCH_SCHEMA, FORGET_SCHEMA, PROFILE_SCHEMA]:
- schema = json.loads(json.dumps(base)) # deep copy
- schema["parameters"]["properties"]["container_tag"] = container_param
- schemas.append(schema)
- return with_kebab_aliases(schemas)
+ schemas = [json.loads(json.dumps(base)) for base in _BASE_SCHEMAS] # deep copies
+ if self._enable_custom_containers:
+ for schema in schemas: # multi-container mode: every tool takes an optional container_tag
+ schema["parameters"]["properties"]["container_tag"] = {
+ "type": "string",
+ "description": f"Optional container tag. Allowed: {', '.join(self._allowed_containers)}. Defaults to primary ({self._container_tag}).",
+ }
+ # Kebab-case aliases are appended after all snake_case schemas (deep-copied, name swapped).
+ return schemas + [{**json.loads(json.dumps(s)), "name": _KEBAB_ALIASES[s["name"]]} for s in schemas]
+
+ def _run_tool(self, args: dict, fail_prefix: str, fn: Callable[[Optional[str]], Any], *,
+ tag_in_response: bool = True) -> str:
+ """Resolve container_tag, run ``fn(tag)``, and JSON-encode its result; errors become tool_error()."""
+ try:
+ tag = self._resolve_tool_container_tag(args)
+ except ValueError as exc:
+ return tool_error(str(exc))
+ try:
+ resp = fn(tag)
+ if tag and tag_in_response:
+ resp["container_tag"] = tag
+ return json.dumps(resp)
+ except Exception as exc:
+ return tool_error(f"{fail_prefix}: {exc}")
def _tool_store(self, args: dict) -> str:
content = str(args.get("content") or "").strip()
if not content:
return tool_error("content is required")
- try:
- tag = self._resolve_tool_container_tag(args)
- except ValueError as exc:
- return tool_error(str(exc))
metadata = args.get("metadata") or {}
if not isinstance(metadata, dict):
metadata = {}
metadata.setdefault("type", _detect_category(content))
metadata.pop("source", None)
- try:
+
+ def _store(tag):
result = self._client.add_memory(content, metadata=metadata, entity_context=self._entity_context, container_tag=tag)
preview = content[:80] + ("..." if len(content) > 80 else "")
- resp: dict[str, Any] = {"saved": True, "id": result.get("id", ""), "preview": preview}
- if tag:
- resp["container_tag"] = tag
- return json.dumps(resp)
- except Exception as exc:
- return tool_error(f"Failed to store memory: {exc}")
+ return {"saved": True, "id": result.get("id", ""), "preview": preview}
+
+ return self._run_tool(args, "Failed to store memory", _store)
def _tool_search(self, args: dict) -> str:
query = str(args.get("query") or "").strip()
if not query:
return tool_error("query is required")
- try:
- tag = self._resolve_tool_container_tag(args)
- except ValueError as exc:
- return tool_error(str(exc))
- try:
- limit = max(1, min(20, int(args.get("limit", 5) or 5)))
- except Exception:
- limit = 5
- try:
- results = self._client.search_memories(query, limit=limit, container_tag=tag)
+ limit = _clamp_number(args.get("limit", 5) or 5, 5, 1, 20, int)
+
+ def _search(tag):
formatted = []
- for item in results:
- entry: dict[str, Any] = {"id": item.get("id", ""), "content": item.get("memory", "")}
- if item.get("similarity") is not None:
- try:
- entry["similarity"] = round(float(item["similarity"]) * 100)
- except Exception:
- pass
- formatted.append(entry)
- resp: dict[str, Any] = {"results": formatted, "count": len(formatted)}
- if tag:
- resp["container_tag"] = tag
- return json.dumps(resp)
- except Exception as exc:
- return tool_error(f"Search failed: {exc}")
+ for item in self._client.search_memories(query, limit=limit, container_tag=tag):
+ pct = _similarity_pct(item.get("similarity"))
+ formatted.append({"id": item.get("id", ""), "content": item.get("memory", ""),
+ **({"similarity": pct} if pct is not None else {})})
+ return {"results": formatted, "count": len(formatted)}
+
+ return self._run_tool(args, "Search failed", _search)
def _tool_forget(self, args: dict) -> str:
memory_id = str(args.get("id") or "").strip()
query = str(args.get("query") or "").strip()
if not memory_id and not query:
return tool_error("Provide either id or query")
- try:
- tag = self._resolve_tool_container_tag(args)
- except ValueError as exc:
- return tool_error(str(exc))
- try:
+
+ def _forget(tag):
if memory_id:
self._client.forget_memory(memory_id, container_tag=tag)
- return json.dumps({"forgotten": True, "id": memory_id})
- return json.dumps(self._client.forget_by_query(query, container_tag=tag))
- except Exception as exc:
- return tool_error(f"Forget failed: {exc}")
+ return {"forgotten": True, "id": memory_id}
+ return self._client.forget_by_query(query, container_tag=tag)
+
+ return self._run_tool(args, "Forget failed", _forget, tag_in_response=False)
def _tool_profile(self, args: dict) -> str:
query = str(args.get("query") or "").strip() or None
- try:
- tag = self._resolve_tool_container_tag(args)
- except ValueError as exc:
- return tool_error(str(exc))
- try:
+
+ def _profile(tag):
profile = self._client.get_profile(query=query, container_tag=tag)
- sections = []
- if profile["static"]:
- sections.append("## User Profile (Persistent)\n" + "\n".join(f"- {item}" for item in profile["static"]))
- if profile["dynamic"]:
- sections.append("## Recent Context\n" + "\n".join(f"- {item}" for item in profile["dynamic"]))
- resp: dict[str, Any] = {
- "profile": "\n\n".join(sections),
- "static_count": len(profile["static"]),
- "dynamic_count": len(profile["dynamic"]),
- }
- if tag:
- resp["container_tag"] = tag
- return json.dumps(resp)
- except Exception as exc:
- return tool_error(f"Profile failed: {exc}")
+ return {"profile": "\n\n".join(_profile_sections(profile["static"], profile["dynamic"])),
+ "static_count": len(profile["static"]), "dynamic_count": len(profile["dynamic"])}
+
+ return self._run_tool(args, "Profile failed", _profile)
def handle_tool_call(self, tool_name: str, args: Dict[str, Any], **kwargs) -> str:
if not self._active or not self._client:
return tool_error("Supermemory is not configured")
- aliases = {
- "supermemory-save": "supermemory_store",
- "supermemory-search": "supermemory_search",
- "supermemory-forget": "supermemory_forget",
- "supermemory-profile": "supermemory_profile",
- }
- tool_name = aliases.get(tool_name, tool_name)
- if tool_name == "supermemory_store":
- return self._tool_store(args)
- if tool_name == "supermemory_search":
- return self._tool_search(args)
- if tool_name == "supermemory_forget":
- return self._tool_forget(args)
- if tool_name == "supermemory_profile":
- return self._tool_profile(args)
- return tool_error(f"Unknown tool: {tool_name}")
+ tool_name = _ALIAS_TO_TOOL.get(tool_name, tool_name)
+ handler = self._TOOL_HANDLERS.get(tool_name)
+ return handler(self, args) if handler else tool_error(f"Unknown tool: {tool_name}")
+
+ # snake_case tool name -> handler; kebab aliases are folded in via _ALIAS_TO_TOOL first.
+ _TOOL_HANDLERS = {"supermemory_store": _tool_store, "supermemory_search": _tool_search,
+ "supermemory_forget": _tool_forget, "supermemory_profile": _tool_profile}
def register(ctx):