Skip to content

The agent that grows with you

fix: restore catalog Hindsight and harden installers and test guards

ethernetf91bd82286e6
diff --git a/COMPAT_MANIFEST.md b/COMPAT_MANIFEST.md
index 0aeb7853fb1..d57f9c4e719 100644
--- a/COMPAT_MANIFEST.md
+++ b/COMPAT_MANIFEST.md
@@ -2425,13 +2425,6 @@ to the public equivalent or the new module. Test monkeypatch seams are likewise
| `save_b64_image` | moved-lazy | `agent.image_gen_provider` |
| `save_url_image` | moved-lazy | `agent.image_gen_provider` |
-### `plugins.memory.hindsight`
-
-| name | kind | new location |
-|---|---|---|
-| `dataclass` | import | `dataclasses` |
-| `importlib` | import | `importlib` |
-
### `plugins.memory.honcho`
| name | kind | new location |
diff --git a/compat_manifest.json b/compat_manifest.json
index 101e161103f..c809e031a98 100644
--- a/compat_manifest.json
+++ b/compat_manifest.json
@@ -7910,18 +7910,6 @@
"kind": "moved-lazy",
"target": "agent.image_gen_provider"
},
- {
- "facade": "plugins.memory.hindsight",
- "name": "dataclass",
- "kind": "import",
- "target": "dataclasses"
- },
- {
- "facade": "plugins.memory.hindsight",
- "name": "importlib",
- "kind": "import",
- "target": "importlib"
- },
{
"facade": "plugins.memory.honcho",
"name": "CONCLUDE_SCHEMA",
@@ -12519,4 +12507,4 @@
"target": "(deleted)"
}
]
-}
+}
\ No newline at end of file
diff --git a/hermes_cli/AGENTS.md b/hermes_cli/AGENTS.md
index 3ef2a5e9de7..ba5844fbce5 100644
--- a/hermes_cli/AGENTS.md
+++ b/hermes_cli/AGENTS.md
@@ -173,7 +173,7 @@ it guards. `plan → snapshot → apply → restart-per-kind → verify → repo
this owner; never reload or purge modules to continue in the old interpreter. The parent keeps
the lock, waits, and accepts only a correlated terminal result. `cmd_update` still finalizes
early failures and missing/killed-child outcomes; PM refusal data survives the handoff.
- See `docs/source-update-completion.md`. A begun-but-unwritten receipt is a bug.
+ See `website/docs/developer-guide/source-update-completion.md`. A begun-but-unwritten receipt is a bug.
- **Nothing runs pulled code in the pre-pull interpreter.** This tree finishes updates through
`update_completion.run_completion` / `_update_takeover.py`.
`hermes_cli/update_handoff.py` and `hermes_cli/update_serve_obligations.py` are the
diff --git a/hermes_cli/banner.py b/hermes_cli/banner.py
index f2fca90ee1c..8466f2e56fb 100644
--- a/hermes_cli/banner.py
+++ b/hermes_cli/banner.py
@@ -169,8 +169,8 @@ def get_git_banner_state(repo_dir: Optional[Path] = None) -> Optional[dict]:
def _baked_banner_state() -> Optional[dict]:
"""Banner state from the baked build SHA (Docker image path), or None."""
def _baked():
- from hermes_cli.build_info import get_build_sha
- return get_build_sha(short=8)
+ from hermes_cli.version_info import get_code_identity
+ return get_code_identity().get("short_sha")
baked = _quiet(_baked)
return {"upstream": baked, "local": baked, "ahead": 0} if baked else None
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index 7f427c49c5b..10163757493 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -1291,7 +1291,7 @@ DEFAULT_CONFIG = {
# Periodic built-in memory review; 0 when an external provider auto-extracts.
"nudge_interval": 10,
# External memory provider plugin (empty = built-in only); only ONE at a time: "openviking",
- # "mem0", "hindsight", "holographic", "retaindb", "byterover".
+ # "mem0", "holographic", "retaindb", "byterover", or a catalog-installed one ("hindsight").
"provider": "",
},
# Subagent delegation — override the provider:model used by delegate_task so children run on a
diff --git a/hermes_cli/plugins_updates.py b/hermes_cli/plugins_updates.py
index 450b403824d..b0389ae4869 100644
--- a/hermes_cli/plugins_updates.py
+++ b/hermes_cli/plugins_updates.py
@@ -368,6 +368,8 @@ def default_fetch(url: str) -> str:
import urllib.request
with urllib.request.urlopen(https_update_url(url), timeout=_FETCH_TIMEOUT) as resp:
+ # urllib follows redirects automatically; do not trust a feed moved onto plaintext.
+ https_update_url(resp.geturl())
data = resp.read(_MAX_FEED_BYTES)
return data.decode("utf-8", errors="replace")
diff --git a/hermes_cli/subcommands/memory.py b/hermes_cli/subcommands/memory.py
index d11565f3cfa..70992b14d22 100644
--- a/hermes_cli/subcommands/memory.py
+++ b/hermes_cli/subcommands/memory.py
@@ -12,8 +12,9 @@ def build_memory_parser(subparsers, *, cmd_memory: Callable) -> None:
memory_parser = subparsers.add_parser(
"memory", help="Configure external memory provider",
description="Set up and manage external memory provider plugins.\n\n"
- "Available providers: honcho, openviking, mem0, hindsight,\n"
- "holographic, retaindb, byterover.\n\n"
+ "Bundled providers: honcho, openviking, mem0, holographic,\n"
+ "retaindb, byterover. Catalog providers (e.g. hindsight):\n"
+ "hermes plugins install <name>.\n\n"
"Only one external provider can be active at a time.\n"
"Built-in memory (MEMORY.md/USER.md) is always active.")
memory_sub = memory_parser.add_subparsers(dest="memory_command")
diff --git a/hermes_cli/tips.py b/hermes_cli/tips.py
index 0fb8b5f2483..b3a7c365e64 100644
--- a/hermes_cli/tips.py
+++ b/hermes_cli/tips.py
@@ -224,7 +224,7 @@ TIPS = [
# --- Plugins ---
"Three plugin types: general (tools/hooks), memory providers, and context engines.",
"hermes plugins install owner/repo installs plugins directly from GitHub.",
- "8 external memory providers available: Honcho, OpenViking, Mem0, Hindsight, and more.",
+ "External memory providers: Honcho, OpenViking, Mem0 bundled; Hindsight and more via hermes plugins install.",
"Plugin hooks include pre/post_tool_call, pre/post_llm_call, and transform_terminal_output for output canonicalization.",
# --- Miscellaneous ---
"Prompt caching (Anthropic) reduces costs by reusing cached system prompt prefixes.",
diff --git a/plugin-catalog/hindsight.yaml b/plugin-catalog/hindsight.yaml
new file mode 100644
index 00000000000..12d6ef141bf
--- /dev/null
+++ b/plugin-catalog/hindsight.yaml
@@ -0,0 +1,22 @@
+name: hindsight
+repo: https://github.com/vectorize-io/hindsight
+sha: 176f8c2de1369f569c489b831d143b78128b5535
+subdir: hindsight-integrations/hermes
+version: "1.0.1"
+description: Hindsight long-term memory provider — knowledge graph, entity resolution and multi-strategy
+ retrieval (recall/reflect/retain tools plus automatic per-turn capture); cloud, local embedded or local
+ external mode. Maintained by Vectorize; the same provider that shipped in-tree. Disclosure — in
+ local_embedded mode the plugin installs the `hindsight-all` PyPI package into the Hermes venv on first
+ use through core's lazy-install path (honours security.allow_lazy_installs), and `hermes memory setup`
+ fetches its bank-template catalog from raw.githubusercontent.com (vectorize-io/hindsight main).
+maintainer: vectorize-io
+tier: community
+category: memory
+requires_hermes: ">=0.21.4"
+docs_url: https://hindsight.vectorize.io/sdks/integrations/hermes
+image: https://raw.githubusercontent.com/vectorize-io/hindsight/176f8c2de1369f569c489b831d143b78128b5535/hindsight-integrations/hermes/docs/banner.png
+capabilities:
+ provides_tools: []
+ provides_hooks: []
+ provides_middleware: []
+ requires_env: []
diff --git a/plugins/AGENTS.md b/plugins/AGENTS.md
index ec6b44a5c4d..93548f6472a 100644
--- a/plugins/AGENTS.md
+++ b/plugins/AGENTS.md
@@ -17,7 +17,9 @@ command. A hook with no concrete consumer is speculative infrastructure and is r
## What may live in this tree (policy)
- **No new in-tree memory providers (May 2026).** `plugins/memory/` is closed (honcho, mem0,
- supermemory, byterover, hindsight, holographic, openviking, retaindb stay; bug fixes welcome). New
+ supermemory, byterover, holographic, openviking, retaindb stay; bug fixes welcome; hindsight moved
+ to the plugin catalog in Sep 2026 — `plugin-catalog/hindsight.yaml`, auto-installed by
+ `hermes_cli/memory_provider_migration.py` for homes still configured for it). New
backends ship as standalone repos implementing the same `MemoryProvider` ABC, discovered through
the same path, integrated via `hermes memory setup` / `post_setup()`.
- **No new third-party-product plugins (June 2026).** Observability/metrics backends, vendor SaaS
@@ -119,4 +121,4 @@ External-plugin compat is handled ONCE here — never add per-PR re-export shims
`tests/plugins/`. Load through real discovery with a temp `HERMES_HOME`; assert behaviour (tool
registered, hook fired with expected kwargs), not counts. Opt-in telemetry rule applies to plugins
-too: no attribution tag ships by default (`tests/plugins/memory/test_hindsight_provider.py`).
+too: no attribution tag ships by default.
diff --git a/plugins/memory/hindsight/README.md b/plugins/memory/hindsight/README.md
deleted file mode 100644
index 1c0834eab0c..00000000000
--- a/plugins/memory/hindsight/README.md
+++ /dev/null
@@ -1,166 +0,0 @@
-# Hindsight Memory Provider
-
-Long-term memory with knowledge graph, entity resolution, and multi-strategy retrieval. Supports cloud, local embedded, and local external modes.
-
-## Requirements
-
-- **Cloud:** API key from [ui.hindsight.vectorize.io](https://ui.hindsight.vectorize.io)
-- **Local Embedded:** API key for a supported LLM provider (OpenAI, Anthropic, Gemini, Groq, OpenRouter, MiniMax, Ollama, or any OpenAI-compatible endpoint). Embeddings and reranking run locally — no additional API keys needed.
-- **Local External:** A running Hindsight instance (Docker or self-hosted) reachable over HTTP.
-
-## Setup
-
-```bash
-hermes memory setup # select "hindsight"
-```
-
-The setup wizard installs dependencies automatically via `uv`, walks you through configuration, and offers to seed the bank with a **starter memory template** (a curated set of dispositions/instructions for common agent roles) — you can skip it, and it warns before overwriting an already-configured bank.
-
-Or manually (cloud mode with defaults):
-```bash
-hermes config set memory.provider hindsight
-echo "HINDSIGHT_API_KEY=your-key" >> ~/.hermes/.env
-```
-
-### Cloud
-
-Connects to the Hindsight Cloud API. Requires an API key from [ui.hindsight.vectorize.io](https://ui.hindsight.vectorize.io).
-
-### Local Embedded
-
-Hermes spins up a local Hindsight daemon with built-in PostgreSQL. Requires an LLM API key for memory extraction and synthesis. The daemon starts automatically in the background on first use and stops after 5 minutes of inactivity.
-
-Supports any OpenAI-compatible LLM endpoint (llama.cpp, vLLM, LM Studio, etc.) — pick `openai_compatible` as the provider and enter the base URL.
-
-The embedded runtime lives in separately resolved generations under
-`$HERMES_HOME/profiles/Hindsight/env/`. `active.json` selects the current
-generation. Its own interpreter runs `hindsight-embed` and `hindsight-api-slim`;
-Hermes uses the HTTP client instead of importing that server into its main environment.
-
-A failed runtime build preserves the previous generation. Re-run
-`hermes memory setup` and select Local Embedded to repair it. Initial model
-loading can require network access and several minutes.
-
-Hermes records side-environment preparation and daemon-bridge errors in its
-normal logs. The sidecar manager owns its separate daemon logs. The
-`hindsight-embed` CLI is inside the selected generation, not automatically on
-the host PATH.
-
-### Local External
-
-Points the plugin at an existing Hindsight instance you're already running (Docker, self-hosted, etc.). No daemon management — just a URL and an optional API key.
-
-## Config
-
-Config file: `~/.hermes/hindsight/config.json`
-
-### Connection
-
-| Key | Default | Description |
-|-----|---------|-------------|
-| `mode` | `cloud` | `cloud`, `local_embedded`, or `local_external` |
-| `api_url` | `https://api.hindsight.vectorize.io` | API URL (cloud and local_external modes) |
-
-### Memory Bank
-
-| Key | Default | Description |
-|-----|---------|-------------|
-| `bank_id` | `hermes` | Memory bank name (static fallback used when `bank_id_template` is unset or resolves empty) |
-| `bank_id_template` | — | Optional template to derive the bank name dynamically. Placeholders: `{profile}`, `{workspace}`, `{platform}`, `{user}`, `{session}`. Example: `hermes-{profile}` isolates memory per active Hermes profile. Empty placeholders collapse cleanly (e.g. `hermes-{user}` with no user becomes `hermes`). |
-| `bank_mission` | — | Reflect mission (identity/framing for reflect reasoning). Applied via Banks API. |
-| `bank_retain_mission` | — | Retain mission (steers what gets extracted). Applied via Banks API. |
-
-### Recall
-
-| Key | Default | Description |
-|-----|---------|-------------|
-| `recall_budget` | `mid` | Recall thoroughness: `low` / `mid` / `high` |
-| `recall_prefetch_method` | `recall` | Auto-recall method: `recall` (raw facts) or `reflect` (LLM synthesis) |
-| `recall_max_tokens` | `4096` | Maximum tokens for recall results |
-| `recall_max_input_chars` | `800` | Maximum input query length for auto-recall |
-| `recall_prompt_preamble` | — | Custom preamble for recalled memories in context |
-| `recall_tags` | — | Tags to filter when searching memories |
-| `recall_tags_match` | `any` | Tag matching mode: `any` / `all` / `any_strict` / `all_strict` |
-| `recall_types` | `observation` | Fact types surfaced by recall (both auto-recall and the `hindsight_recall` tool). Comma-separated string or JSON list. **Default narrowed to `observation` only** (see "Behavior change" below). Set to `observation,world,experience` to also include raw facts. |
-| `auto_recall` | `true` | Automatically recall memories before each turn |
-| `recall_sync` | `false` | Recall synchronously against the *current* message each turn (higher relevance, adds recall latency). Default off: recall runs in the background and is injected on the next turn. |
-| `recall_indicator` | `true` | Show a `👁️ Hindsight — recalled N memories` status line when auto-recall injects memory. Turn off for customer-facing agents. |
-
-> **Behavior change — `recall_types` defaults to `observation` only.**
->
-> Previously recall returned all three fact types. It now returns only observations.
->
-> Per [Hindsight's docs](https://hindsight.vectorize.io/developer/observations), observations are the **consolidated** knowledge layer Hindsight builds on top of raw facts: deduplicated beliefs grounded in evidence, refined as new facts arrive, with proof counts and freshness signals. Raw `world` / `experience` facts are the individual supporting evidence that feeds them. For per-turn context injection, observations are denser per token and avoid feeding the model multiple raw facts that one observation already summarizes.
->
-> Restore the broad recall with `"recall_types": "observation,world,experience"` (string or JSON list) in `~/.hermes/hindsight/config.json`. This applies to **both** auto-recall and the `hindsight_recall` tool — both read the same `recall_types` setting (the tool schema has no per-call `types` argument), so narrowing the default narrows both paths.
-
-### Retain
-
-| Key | Default | Description |
-|-----|---------|-------------|
-| `auto_retain` | `true` | Automatically retain conversation turns |
-| `retain_async` | `true` | Process retain asynchronously on the Hindsight server |
-| `retain_every_n_turns` | `1` | Retain every N turns (1 = every turn) |
-| `retain_context` | `conversation between Hermes Agent and the User` | Context label for retained memories |
-| `retain_tags` | — | Default tags applied to retained memories; merged with per-call tool tags |
-| `retain_source` | — | Opt-in `metadata.source` attached to retained memories (identifies the storing client, e.g. `hermes`). Empty by default — no attribution tag ships unless you set it. |
-| `retain_indicator` | `true` | Show a `👁️ Hindsight — saving to memory…` status line when a turn is saved. Turn off for customer-facing agents. |
-| `retain_user_prefix` | `User` | Label used before user turns in auto-retained transcripts |
-| `retain_assistant_prefix` | `Assistant` | Label used before assistant turns in auto-retained transcripts |
-
-### Integration
-
-| Key | Default | Description |
-|-----|---------|-------------|
-| `memory_mode` | `hybrid` | How memories are integrated into the agent |
-
-**memory_mode:**
-- `hybrid` — automatic context injection + tools available to the LLM
-- `context` — automatic injection only, no tools exposed
-- `tools` — tools only, no automatic injection
-
-### Local Embedded LLM
-
-| Key | Default | Description |
-|-----|---------|-------------|
-| `llm_provider` | `openai` | `openai`, `anthropic`, `gemini`, `groq`, `openrouter`, `minimax`, `ollama`, `lmstudio`, `openai_compatible` |
-| `llm_model` | per-provider | Model name (e.g. `gpt-4o-mini`, `qwen/qwen3.5-9b`) |
-| `llm_base_url` | — | Endpoint URL for `openai_compatible` (e.g. `http://192.168.1.10:8080/v1`) |
-
-The LLM API key is stored in `~/.hermes/.env` as `HINDSIGHT_LLM_API_KEY`.
-
-The embedded daemon is a subprocess that cannot see the per-turn secret
-scope, so it reads the key from `~/.hindsight/profiles/<profile>.env`
-(materialized owner-only at setup and on config change). Key resolution
-order is explicit config → secret scope → the on-disk profile env, and the
-rewrite path is fail-closed: a build with no key never clobbers a profile
-file that already holds one.
-
-## Tools
-
-Available in `hybrid` and `tools` memory modes:
-
-| Tool | Description |
-|------|-------------|
-| `hindsight_retain` | Store information with auto entity extraction; supports optional per-call `tags` |
-| `hindsight_recall` | Multi-strategy search (semantic + entity graph) |
-| `hindsight_reflect` | Cross-memory synthesis (LLM-powered) |
-
-## Environment Variables
-
-| Variable | Description |
-|----------|-------------|
-| `HINDSIGHT_API_KEY` | API key for Hindsight Cloud |
-| `HINDSIGHT_LLM_API_KEY` | LLM API key for local mode |
-| `HINDSIGHT_API_LLM_BASE_URL` | LLM Base URL for local mode (e.g. OpenRouter) |
-| `HINDSIGHT_API_URL` | Override API endpoint |
-| `HINDSIGHT_BANK_ID` | Override bank name |
-| `HINDSIGHT_BUDGET` | Override recall budget |
-| `HINDSIGHT_MODE` | Override mode (`cloud`, `local_embedded`, `local_external`) |
-
-## Client Version
-
-The client version comes from the `hindsight` extra in `pyproject.toml` and
-`uv.lock`. PM prepares client dependency changes without replacing libraries
-already imported by Hermes. Restart Hermes when the dependency operation
-reports that the new environment is selected.
diff --git a/plugins/memory/hindsight/__init__.py b/plugins/memory/hindsight/__init__.py
deleted file mode 100644
index 3f379d46b0a..00000000000
--- a/plugins/memory/hindsight/__init__.py
+++ /dev/null
@@ -1,1208 +0,0 @@
-"""Hindsight memory plugin — MemoryProvider with knowledge graph, entity resolution
-and multi-strategy retrieval; cloud (API key), local_external, or local_embedded.
-
-Config: $HERMES_HOME/hindsight/config.json (profile-scoped), else ~/.hindsight/
-config.json (legacy, shared), else env: HINDSIGHT_API_KEY / BANK_ID / BUDGET /
-API_URL / MODE / TIMEOUT / IDLE_TIMEOUT / RETAIN_TAGS / RETAIN_OBSERVATION_SCOPES /
-RETAIN_SOURCE / RETAIN_USER_PREFIX / RETAIN_ASSISTANT_PREFIX, and
-HINDSIGHT_EMBED_PORT_HEALTH_GRACE_TIMEOUT (config.json port_health_grace_timeout).
-"""
-
-from __future__ import annotations
-
-import asyncio
-import atexit
-import contextlib
-import json
-import logging
-import os
-import queue
-import sys
-import threading
-import time
-from datetime import datetime, timezone
-from pathlib import Path
-from typing import Any, Callable, Dict, List, Optional
-
-from agent.memory_provider import MemoryProvider, RecallStatus, spawn_context_thread
-from agent.secret_scope import UnscopedSecretError, get_secret
-from hermes_cli.config import cfg_get
-from hermes_constants import get_hermes_home
-from hermes_time import now as _hermes_now
-from tools.registry import tool_error
-from utils import read_json_or_empty
-
-from .embedded import (
- _RETRIABLE_CONNECTION_MARKERS, _build_embedded_profile_env,
- _check_local_runtime, _embedded_profile_env_path,
- _load_simple_env, _local_runtime_hint, _materialize_embedded_profile_env,
- _may_rewrite_profile_env,
-)
-from .embedded_runtime import ensure_daemon_and_url as _start_sideenv_daemon
-from .settings import (
- _DEFAULT_API_URL, _DEFAULT_IDLE_TIMEOUT, _DEFAULT_LOCAL_URL, _DEFAULT_RETAIN_SOURCE,
- _DEFAULT_TIMEOUT, _HINDSIGHT_GLYPH, _MIN_VERSION_FOR_UPDATE_MODE_APPEND,
- _PROVIDER_DEFAULT_MODELS, _VALID_BUDGETS, _daemon_llm_provider,
- _normalize_observation_scopes, _normalize_retain_tags, _parse_int_setting,
- _resolve_bank_id_template,
-)
-
-logger = logging.getLogger(__name__)
-
-_LOCAL_MODES = {"local", "local_embedded"}
-_RETAIN_CONTEXT_DEFAULT = "conversation between Hermes Agent and the User"
-
-
-def _ensure_client_dependency() -> None:
- """Make the pinned ``hindsight`` extra importable before the client import."""
- try:
- from pm import ensure_import
- ensure_import("hindsight")
- except Exception as exc:
- raise ImportError(str(exc)) from exc
-
-
-def _scoped_setting(name: str, default: str = "") -> str:
- """Profile-scoped read of a retain SHAPING value, with the provider's own default on a miss.
-
- Under ``gateway.multiplex_profiles`` ``os.environ`` holds the DEFAULT profile's ``.env``, so a miss
- is a miss — never ``os.environ`` (same rule as the daemon's key and base URL in ``embedded.py``).
- Single-profile deployments are unchanged: with no scope installed ``get_secret`` still reads the
- process env, where the value IS this profile's own.
-
- Deliberately narrower than a bare ``get_secret``: this helper is only for presentation shaping
- (retain source label, speaker prefixes, tags). The isolation-critical values — ``mode``,
- ``apiKey`` and the ``bankId`` data partition — read through bare ``get_secret`` above and so
- still fail loud on a scopeless multiplexed read, matching the other scoped credential readers.
- In ``_load_config`` that read happens FIRST, so a missing scope raises on ``HINDSIGHT_MODE``
- before this helper is ever reached; swallowing here therefore cannot mask an isolation failure.
- What it does avoid is losing the whole memory provider (``initialize`` failing, and the manager
- logging + dropping it) because a speaker prefix could not be resolved.
- """
- try:
- value = get_secret(name, default)
- except UnscopedSecretError:
- return default
- return default if value is None else value
-
-
-def _cloud_api_key(config: dict) -> str:
- return config.get("apiKey") or config.get("api_key") or get_secret("HINDSIGHT_API_KEY", "")
-
-
-# update_mode='append' capability (Hindsight >= 0.5.0), cached per (API URL, key fingerprint)
-# per process so every provider on the same API+key shares one /version round trip. A failed probe
-# caches False, so the key must include the credential or one profile's 401 would silently downgrade
-# a sibling profile that shares the URL with a valid key.
-_append_capability_cache: Dict[tuple[str, str | None], bool] = {}
-_append_capability_lock = threading.Lock()
-
-
-def _fetch_hindsight_api_version(api_url: str, api_key: str | None = None,
- timeout: float = 5.0) -> str | None:
- """GET ``<api_url>/version`` -> version string, or None on any failure (= legacy API)."""
- import urllib.request
- if not api_url:
- return None
- url = api_url.rstrip("/") + "/version"
- req = urllib.request.Request(url, headers={"Authorization": f"Bearer {api_key}"} if api_key else {})
- try:
- with urllib.request.urlopen(req, timeout=timeout) as resp: # noqa: S310
- data = json.loads(resp.read().decode("utf-8", errors="replace"))
- except Exception as exc:
- logger.debug("Hindsight /version probe failed for %s: %s", url, exc)
- return None
- version = (data.get("version") or data.get("api_version")) if isinstance(data, dict) else None
- return str(version) if version else None
-
-
-def _check_api_supports_update_mode_append(api_url: str, api_key: str | None = None) -> bool:
- """Cached ``update_mode='append'`` check for *api_url*. False on any probe failure
- (safe default: per-process document_id, no update_mode = resume-overwrite fix intact).
-
- Probes once per URL per process. See #6654.
- """
- if not api_url:
- return False
- from agent.credential_persistence import fingerprint_secret_value
-
- cache_key = (api_url, fingerprint_secret_value(api_key))
- with _append_capability_lock:
- if cache_key in _append_capability_cache:
- return _append_capability_cache[cache_key]
- version = _fetch_hindsight_api_version(api_url, api_key)
- try: # missing/invalid version -> unsupported
- from packaging.version import Version
- supported = bool(version) and Version(version) >= Version(_MIN_VERSION_FOR_UPDATE_MODE_APPEND)
- except Exception:
- supported = False
- with _append_capability_lock:
- # A concurrent probe may have filled the cache meanwhile; its answer wins.
- supported = _append_capability_cache.setdefault(cache_key, supported)
- if supported:
- logger.debug("Hindsight API %s version %s supports update_mode='append'", api_url, version)
- else:
- logger.warning("Hindsight API at %s reports version %r, older than %s. "
- "Falling back to per-process document_id — retains across "
- "processes/sessions create separate documents instead of "
- "appending to a session-scoped one. Upgrade Hindsight to "
- "%s+ to enable update_mode='append' deduplication.",
- api_url, version, _MIN_VERSION_FOR_UPDATE_MODE_APPEND, _MIN_VERSION_FOR_UPDATE_MODE_APPEND)
- return supported
-
-
-# One long-lived event loop per process for Hindsight async calls; ephemeral
-# loops would leak aiohttp sessions.
-_loop: asyncio.AbstractEventLoop | None = None
-_loop_thread: threading.Thread | None = None
-_loop_lock = threading.Lock()
-
-# Pushed to the per-provider retain queue to wake the writer for a clean exit.
-_WRITER_SENTINEL = object()
-
-
-def _get_loop() -> asyncio.AbstractEventLoop:
- """Return a long-lived event loop running on a background thread."""
- global _loop, _loop_thread
- with _loop_lock:
- if _loop is not None and _loop.is_running():
- return _loop
- loop = _loop = asyncio.new_event_loop()
- _loop_thread = threading.Thread(
- target=lambda: (asyncio.set_event_loop(loop), loop.run_forever()), daemon=True, name="hindsight-loop",
- )
- _loop_thread.start()
- return _loop
-
-
-def _run_sync(coro, timeout: float = _DEFAULT_TIMEOUT):
- """Schedule *coro* on the shared loop and block until done."""
- from agent.async_utils import safe_schedule_threadsafe
- future = safe_schedule_threadsafe(coro, _get_loop())
- if future is None:
- raise RuntimeError("Hindsight loop unavailable")
- return future.result(timeout=timeout)
-
-
-RETAIN_SCHEMA = {
- "name": "hindsight_retain",
- "description": (
- "Store information to long-term memory. Hindsight automatically "
- "extracts structured facts, resolves entities, and indexes for retrieval."
- ),
- "parameters": {
- "type": "object",
- "properties": {
- "content": {"type": "string", "description": "The information to store."},
- "context": {"type": "string", "description": "Short label (e.g. 'user preference', 'project decision')."},
- "tags": {"type": "array", "items": {"type": "string"},
- "description": "Optional per-call tags to merge with configured default retain tags."},
- "occurred_at": {"type": "string", "description": (
- "When the remembered event actually happened, as an ISO-8601 date "
- "or datetime (e.g. '2026-08-20' or '2026-08-20T14:30:00+02:00'). "
- "Pass this whenever the memory references a specific event time "
- "('yesterday', 'last Tuesday', 'on March 3rd') so Hindsight can "
- "anchor it on the timeline. Omit for timeless facts/preferences."
- )},
- },
- "required": ["content"],
- },
-}
-
-RECALL_SCHEMA = {
- "name": "hindsight_recall",
- "description": (
- "Search long-term memory. Returns memories ranked by relevance using "
- "semantic search, keyword matching, entity graph traversal, and reranking."
- ),
- "parameters": {"type": "object", "required": ["query"],
- "properties": {"query": {"type": "string", "description": "What to search for."}}},
-}
-
-REFLECT_SCHEMA = {
- "name": "hindsight_reflect",
- "description": (
- "Synthesize a reasoned answer from long-term memories. Unlike recall, "
- "this reasons across all stored memories to produce a coherent response."
- ),
- "parameters": {"type": "object", "required": ["query"],
- "properties": {"query": {"type": "string", "description": "The question to reflect on."}}},
-}
-
-
-def _load_config() -> dict:
- """$HERMES_HOME/hindsight/config.json (profile-scoped), else ~/.hindsight/config.json
- (legacy, shared), else environment variables."""
- for path in (get_hermes_home() / "hindsight" / "config.json", Path.home() / ".hindsight" / "config.json"):
- # A corrupt (or empty) file falls through to the next source, as before the dedup.
- if path.exists() and (data := read_json_or_empty(path)):
- return data
- # Mode, bank (the data partition), endpoint and retain shaping are per-profile .env values like
- # the key beside them: read through the secret scope so a multiplexed secondary never inherits
- # the default profile's bank/mode. Tuning knobs (timeouts, budget) stay process-global.
- return {
- "mode": get_secret("HINDSIGHT_MODE", "") or "cloud",
- "apiKey": get_secret("HINDSIGHT_API_KEY", ""),
- "timeout": _parse_int_setting(os.environ.get("HINDSIGHT_TIMEOUT"), _DEFAULT_TIMEOUT),
- "idle_timeout": _parse_int_setting(os.environ.get("HINDSIGHT_IDLE_TIMEOUT"), _DEFAULT_IDLE_TIMEOUT),
- "retain_tags": get_secret("HINDSIGHT_RETAIN_TAGS", "") or "",
- "observation_scopes": get_secret("HINDSIGHT_RETAIN_OBSERVATION_SCOPES", "") or "",
- "retain_source": _scoped_setting("HINDSIGHT_RETAIN_SOURCE", _DEFAULT_RETAIN_SOURCE),
- "retain_user_prefix": _scoped_setting("HINDSIGHT_RETAIN_USER_PREFIX", "User"),
- "retain_assistant_prefix": _scoped_setting("HINDSIGHT_RETAIN_ASSISTANT_PREFIX", "Assistant"),
- "banks": {"hermes": {"bankId": get_secret("HINDSIGHT_BANK_ID", "") or "hermes",
- "budget": os.environ.get("HINDSIGHT_BUDGET", "mid"), "enabled": True}},
- }
-
-
-def _event_timestamp() -> str:
- """Configured Hermes event time with an explicit UTC offset."""
- event_time = _hermes_now()
- # hermes_time.now() is aware; guard a replacement clock emitting offset-less dates.
- if event_time.tzinfo is None or event_time.utcoffset() is None:
- event_time = event_time.astimezone()
- return event_time.isoformat(timespec="seconds")
-
-
-def _mint_document_id(session_id: str) -> str:
- """Per-process document id: reusing session_id alone overwrote the document on
- /resume (the reloaded session's first retain replaced the stored content)."""
- return f"{session_id}-{datetime.now().strftime('%Y%m%d_%H%M%S_%f')}"
-
-
-# initialize() kwargs copied verbatim (str, stripped) onto ``self._<name>``.
-_SESSION_KWARGS = (
- "platform", "user_id", "user_name", "chat_id", "chat_name", "chat_type",
- "thread_id", "agent_identity", "agent_workspace",
-)
-# Retain metadata keys, each stamped from the attribute of the same name when set.
-_METADATA_ATTRS = (
- "session_id", "platform", "user_id", "user_name", "chat_id", "chat_name",
- "chat_type", "thread_id", "agent_identity",
-)
-_SYSTEM_PROMPT_TAILS = {
- "context": "Relevant memories are automatically injected into context.",
- "tools": ("Use hindsight_recall to search, hindsight_reflect for synthesis, "
- "hindsight_retain to store facts."),
- "hybrid": ("Relevant memories are automatically injected into context. "
- "Use hindsight_recall to search, hindsight_reflect for synthesis, "
- "hindsight_retain to store facts."),
-}
-
-
-class HindsightMemoryProvider(MemoryProvider):
- """Hindsight long-term memory with knowledge graph and multi-strategy retrieval."""
-
- # Each server-side op status poll is a round trip — coarser than the 0.05s queue poll.
- _RETAIN_OP_POLL_INTERVAL_S = 0.5
-
- def backup_paths(self) -> List[str]:
- """Legacy shared config + embedded-mode profile env files live under ~/.hindsight."""
- with contextlib.suppress(Exception):
- return [str(Path.home() / ".hindsight")]
- return []
-
- def __init__(self):
- self._config = self._api_key = self._client = None
- self._api_url, self._llm_base_url, self._mode = _DEFAULT_API_URL, "", "cloud"
- self._timeout, self._idle_timeout = _DEFAULT_TIMEOUT, _DEFAULT_IDLE_TIMEOUT
- self._bank_id, self._budget, self._bank_id_template = "hermes", "mid", ""
- self._bank_mission, self._bank_retain_mission = "", None
- self._memory_mode = "hybrid" # "context", "tools", or "hybrid"
- self._prefetch_method = "recall" # "recall" or "reflect"
- for name in _SESSION_KWARGS:
- setattr(self, f"_{name}", "")
- self._session_id = self._parent_session_id = self._document_id = ""
- self._status_callback: Optional[Callable[[str], None]] = None
-
- # Retain: single-writer model — sync_turn() enqueues, one writer thread
- # drains sequentially (ad-hoc threads raced interpreter shutdown:
- # "cannot schedule new futures" / "Unclosed client session").
- self._retain_queue: queue.Queue = queue.Queue()
- self._writer_thread: threading.Thread | None = None
- self._sync_thread = None # legacy alias external callers may join; points at the writer
- self._shutting_down = threading.Event()
- self._atexit_registered = False
- self._retain_tags: List[str] = []
- self._tags: list[str] | None = None
- self._retain_source = _DEFAULT_RETAIN_SOURCE
- self._retain_user_prefix, self._retain_assistant_prefix = "User", "Assistant"
- self._turn_counter = self._turn_index = 0
- self._session_turns: list[str] = [] # ALL turns for the session
- self._last_retained_turn_count = 0 # append-mode delta watermark
- # Server-side async retain ops still in flight: aretain_batch returns on
- # *acceptance*, not durability, so the prefetch gates on these via
- # get_operation_status (a drained local queue is not a read-after-write signal).
- self._pending_retain_ops: set[str] = set()
- self._pending_retain_ops_lock = threading.Lock()
- self._retain_ops_bank_id = ""
- self._apply_retain_policy({})
-
- # Recall: pending prefetch block + count, and the indicator state (recall_status()).
- self._prefetch_result, self._prefetch_count = "", 0
- self._prefetch_lock = threading.Lock()
- self._prefetch_thread = None
- self._last_recall_returned, self._last_recall_count = False, 0
- self._apply_recall_settings({})
-
- @property
- def name(self) -> str:
- return "hindsight"
-
- def is_available(self) -> bool:
- try:
- cfg = _load_config()
- mode = cfg.get("mode", "cloud")
- if mode in _LOCAL_MODES:
- return _check_local_runtime()[0]
- return mode == "local_external" or bool(
- _cloud_api_key(cfg) or cfg.get("api_url") or get_secret("HINDSIGHT_API_URL", ""))
- except Exception:
- return False
-
- def unavailable_reason(self) -> str:
- """Install hint for an unavailable local_embedded runtime (is_available() gates
- initialize() out, so the hint it would log never fires; agent_init shows this).
-
- ``is_available()`` returns False for local modes when the embedded runtime can't be imported, so
- ``initialize()`` — and the hint it would log — is never reached (#7718). Surface the install
- guidance here, where agent_init warns about an unavailable provider.
- """
- try:
- if _load_config().get("mode", "cloud") not in _LOCAL_MODES:
- return ""
- except Exception:
- return ""
- available, reason = _check_local_runtime()
- return "" if available else _local_runtime_hint(reason).strip()
-
- def save_config(self, values, hermes_home):
- """Merge *values* into $HERMES_HOME/hindsight/config.json."""
- from utils import atomic_json_write
- config_path = Path(hermes_home) / "hindsight" / "config.json"
- atomic_json_write(config_path, {**read_json_or_empty(config_path), **values}, mode=0o600)
-
- def post_setup(self, hermes_home: str, config: dict) -> None:
- """Custom setup wizard — installs only the deps needed for the selected mode."""
- from .setup import run_setup
- run_setup(self, hermes_home, config)
-
- def get_config_schema(self):
- return [
- {"key": "mode", "description": "Connection mode", "default": "cloud", "choices": ["cloud", "local_embedded", "local_external"]},
- # Cloud mode
- {"key": "api_url", "description": "Hindsight Cloud API URL", "default": _DEFAULT_API_URL, "when": {"mode": "cloud"}},
- {"key": "api_key", "description": "Hindsight Cloud API key", "secret": True, "env_var": "HINDSIGHT_API_KEY", "url": "https://ui.hindsight.vectorize.io", "when": {"mode": "cloud"}},
- # Local external mode
- {"key": "api_url", "description": "Hindsight API URL", "default": _DEFAULT_LOCAL_URL, "when": {"mode": "local_external"}},
- {"key": "api_key", "description": "API key (optional)", "secret": True, "env_var": "HINDSIGHT_API_KEY", "when": {"mode": "local_external"}},
- # Local embedded mode
- {"key": "llm_provider", "description": "LLM provider", "default": "openai", "choices": ["openai", "anthropic", "gemini", "groq", "openrouter", "minimax", "ollama", "lmstudio", "openai_compatible"], "when": {"mode": "local_embedded"}},
- {"key": "llm_base_url", "description": "Endpoint URL (e.g. http://192.168.1.10:8080/v1)", "default": "", "when": {"mode": "local_embedded", "llm_provider": "openai_compatible"}},
- {"key": "llm_api_key", "description": "LLM API key (optional for openai_compatible)", "secret": True, "env_var": "HINDSIGHT_LLM_API_KEY", "when": {"mode": "local_embedded"}},
- {"key": "llm_model", "description": "LLM model", "default": "gpt-4o-mini", "default_from": {"field": "llm_provider", "map": _PROVIDER_DEFAULT_MODELS}, "when": {"mode": "local_embedded"}},
- {"key": "bank_id", "description": "Memory bank name (static fallback when bank_id_template is unset)", "default": "hermes"},
- {"key": "bank_id_template", "description": "Optional template to derive bank_id dynamically. Placeholders: {profile}, {workspace}, {platform}, {user}, {session}. Example: hermes-{profile}", "default": ""},
- {"key": "bank_mission", "description": "Mission/purpose description for the memory bank"},
- {"key": "bank_retain_mission", "description": "Custom extraction prompt for memory retention"},
- {"key": "recall_budget", "description": "Recall thoroughness", "default": "mid", "choices": ["low", "mid", "high"]},
- {"key": "memory_mode", "description": "Memory integration mode", "default": "hybrid", "choices": ["hybrid", "context", "tools"]},
- {"key": "recall_prefetch_method", "description": "Auto-recall method", "default": "recall", "choices": ["recall", "reflect"]},
- {"key": "retain_tags", "description": "Default tags applied to retained memories (comma-separated)", "default": ""},
- {"key": "observation_scopes", "description": "How observations are scoped during consolidation: 'combined' (default — one pass over all tags), 'per_tag' (one isolated observation per tag), 'all_combinations' (every tag subset — expensive), or a JSON list of tag-lists for explicit custom scopes. Empty uses Hindsight's 'combined' default.", "default": ""},
- {"key": "retain_source", "description": "Metadata source value attached to retained memories (identifies the client that stored them)", "default": _DEFAULT_RETAIN_SOURCE},
- {"key": "retain_user_prefix", "description": "Label used before user turns in retained transcripts", "default": "User"},
- {"key": "retain_assistant_prefix", "description": "Label used before assistant turns in retained transcripts", "default": "Assistant"},
- {"key": "recall_tags", "description": "Tags to filter when searching memories (comma-separated)", "default": ""},
- {"key": "recall_tags_match", "description": "Tag matching mode for recall", "default": "any", "choices": ["any", "all", "any_strict", "all_strict"]},
- {"key": "recall_types", "description": "Fact types to surface on recall — applies to both auto-recall and the hindsight_recall tool (comma-separated or list). Defaults to observation-only — observations are Hindsight's consolidated, deduplicated, evidence-grounded knowledge layer; raw world/experience facts are the supporting evidence observations already summarize. Set to e.g. 'observation,world,experience' to also include raw facts.", "default": "observation"},
- {"key": "auto_recall", "description": "Automatically recall memories before each turn", "default": True},
- {"key": "recall_sync", "description": "Recall synchronously against the current message before each turn (higher relevance, adds recall latency to the turn). Default off: recall runs in the background and is injected on the next turn.", "default": False},
- {"key": "recall_indicator", "description": "Show a '👁️ Hindsight — recalled N memories' status line when auto-recall injects memory (turn off for customer-facing agents)", "default": True},
- {"key": "retain_indicator", "description": "Show a '👁️ Hindsight — saving to memory…' status line when a turn is saved to memory (turn off for customer-facing agents)", "default": True},
- {"key": "auto_retain", "description": "Automatically retain conversation turns", "default": True},
- {"key": "retain_every_n_turns", "description": "Retain every N turns (1 = every turn)", "default": 1},
- {"key": "retain_async","description": "Process retain asynchronously on the Hindsight server", "default": True},
- {"key": "prefetch_waits_for_retain", "description": "Have the background next-turn prefetch wait for the just-completed retain to become recall-visible on the server (local queue drain + async operation completion) before recalling, so recall includes the just-completed turn (runs off the reply path, adds no response latency)", "default": True},
- {"key": "prefetch_retain_drain_timeout", "description": "Max seconds the background prefetch waits for the retain to become recall-visible (queue drain + server-side completion) before recalling anyway", "default": 10.0},
- {"key": "retain_context", "description": "Context label for retained memories", "default": "conversation between Hermes Agent and the User"},
- {"key": "recall_max_tokens", "description": "Maximum tokens for recall results", "default": 4096},
- {"key": "recall_max_input_chars", "description": "Maximum input query length for auto-recall", "default": 800},
- {"key": "recall_prompt_preamble", "description": "Custom preamble for recalled memories in context"},
- {"key": "timeout", "description": "API request timeout in seconds", "default": _DEFAULT_TIMEOUT},
- {"key": "idle_timeout", "description": "Embedded daemon idle timeout in seconds (0 disables auto-shutdown)", "default": _DEFAULT_IDLE_TIMEOUT, "when": {"mode": "local_embedded"}},
- {"key": "port_health_grace_timeout", "description": "Seconds to wait for a slow daemon /health before treating it as stale (raise on busy/low-resource hosts; blank uses the 30s default)", "default": "", "when": {"mode": "local_embedded"}},
- ]
-
- # -- client -------------------------------------------------------------
-
- def _int_setting(self, key: str, env_var: str, default: int, env_default=None) -> int:
- """Config value if set (explicit 0 preserved), else env var, else default."""
- value = self._config.get(key)
- return _parse_int_setting(os.environ.get(env_var, env_default) if value is None else value, default)
-
- def _new_embedded_client(self):
- """HTTP client against the side-env daemon. The daemon manager runs in the
- isolated side env (its own interpreter → its own hindsight-api binary and
- ProfileManager port allocation); Hermes talks to it over HTTP with the
- pinned main-env hindsight-client — no in-process HindsightEmbedded."""
- cfg = self._config
- profile = cfg.get("profile", "hermes")
- llm_provider = _daemon_llm_provider(cfg.get("llm_provider", ""))
- logger.debug("Creating Hindsight embedded client (profile=%s, provider=%s)", profile, llm_provider)
- self._idle_timeout = self._int_setting(
- "idle_timeout", "HINDSIGHT_IDLE_TIMEOUT", _DEFAULT_IDLE_TIMEOUT, env_default=self._idle_timeout,
- )
- # Starts (or reuses) the side-env daemon; the URL comes from the side env's
- # own ProfileManager/get_url, never a hardcoded port.
- # Fail-closed on key material: when this process holds no key (no secret
- # scope on this thread) but the file does, a rewrite would destroy the
- # only key copy the daemon subprocess can read — leave the file and the
- # running daemon alone rather than restart it keyless.
- changed = _load_simple_env(_embedded_profile_env_path(cfg)) != _build_embedded_profile_env(cfg)
- if changed and not _may_rewrite_profile_env(cfg):
- logger.warning(
- "Hindsight profile env for %r holds an LLM API key this process cannot see "
- "(no secret scope); leaving the file untouched so the daemon keeps its key.", profile)
- changed = False
- if changed:
- _materialize_embedded_profile_env(cfg)
- url = _start_sideenv_daemon(cfg, restart=changed)
- self._api_url = url
- _ensure_client_dependency()
- from hindsight_client import Hindsight
- kwargs = {"base_url": url, "timeout": float(self._timeout or _DEFAULT_TIMEOUT)}
- if self._api_key:
- kwargs["api_key"] = self._api_key
- logger.info("Hindsight embedded: HTTP client ready (profile=%s, url=%s)", profile, url)
- return Hindsight(**kwargs)
-
- def _new_cloud_client(self):
- _ensure_client_dependency()
- from hindsight_client import Hindsight
- kwargs = {"base_url": self._api_url, "timeout": float(self._timeout or _DEFAULT_TIMEOUT)}
- if self._api_key:
- kwargs["api_key"] = self._api_key
- logger.debug("Creating Hindsight cloud client (url=%s, has_key=%s, timeout=%s)",
- self._api_url, bool(self._api_key), kwargs["timeout"])
- return Hindsight(**kwargs)
-
- def _get_client(self):
- """Return the cached Hindsight client (created once, reused)."""
- if self._client is None:
- self._client = self._new_embedded_client() if self._mode == "local_embedded" else self._new_cloud_client()
- return self._client
-
- def _run_sync(self, coro):
- """Schedule *coro* on the shared loop using the configured timeout."""
- return _run_sync(coro, timeout=self._timeout)
-
- def _run_hindsight_operation(self, operation):
- """Run an async client operation; for local_embedded, a stale-daemon
- connection failure recreates the client and retries once."""
- try:
- return self._run_sync(operation(self._get_client()))
- except Exception as exc:
- text = f"{type(exc).__name__}: {exc}".lower()
- if self._mode != "local_embedded" or not any(m in text for m in _RETRIABLE_CONNECTION_MARKERS):
- raise
- logger.info("Hindsight embedded daemon appears unreachable; recreating client and retrying once: %s", exc)
- self._client = None
- self._client = client = self._get_client()
- return self._run_sync(operation(client))
-
- # -- retain writer thread + server-side visibility -------------------------
-
- def _ensure_writer(self) -> None:
- """Lazy-start the single retain-writer thread (tools-only providers never pay for it)."""
- if (thread := self._writer_thread) is not None and thread.is_alive():
- return
- # A previous writer may have exited after shutdown(); allow the fresh one to drain.
- self._shutting_down.clear()
- thread = spawn_context_thread(self._writer_loop, name="hindsight-writer")
- self._writer_thread = self._sync_thread = thread
- thread.start()
-
- def _register_atexit(self) -> None:
- """Idempotent atexit drain: a CLI exit that skips MemoryManager.shutdown_all()
- must not race interpreter teardown."""
- if not self._atexit_registered:
- self._atexit_registered = True
- atexit.register(self._atexit_shutdown)
-
- def _writer_loop(self) -> None:
- """Drain the retain queue serially until the sentinel. A failing job can't
- kill the writer; task_done() always fires so queue.join() works."""
- while True:
- try:
- job = self._retain_queue.get(timeout=1.0)
- except queue.Empty:
- if self._shutting_down.is_set():
- return
- continue
- try:
- if job is _WRITER_SENTINEL:
- return
- job()
- except Exception as exc:
- logger.warning("Hindsight retain failed: %s", exc, exc_info=True)
- finally:
- self._retain_queue.task_done()
-
- def _atexit_shutdown(self) -> None:
- try:
- if not self._shutting_down.is_set():
- self.shutdown()
- except Exception as exc:
- logger.debug("Hindsight atexit shutdown failed: %s", exc)
-
- def _track_retain_ops(self, retain_response, bank_id: str) -> None:
- """Record the async ``operation_id``/``operation_ids`` of an aretain_batch reply
- (pending until recall-visible). No id (older API / sync completion) leaves
- only the local queue drain as a signal."""
- raw_ids = [getattr(retain_response, "operation_id", None), *(getattr(retain_response, "operation_ids", None) or [])]
- if ids := [str(op) for op in raw_ids if op]:
- self._retain_ops_bank_id = bank_id
- with self._pending_retain_ops_lock:
- self._pending_retain_ops.update(ids)
-
- def _is_retain_op_complete(self, bank_id: str, op_id: str) -> bool:
- """True when a server-side retain op is done or gone (completed ops are evicted,
- so 404 = no longer pending). Transient errors -> False, caller keeps waiting."""
- from hindsight_client_api.exceptions import NotFoundException
-
- try:
- resp = self._run_hindsight_operation(
- lambda client: client.operations.get_operation_status(bank_id=bank_id, operation_id=op_id)
- )
- except NotFoundException:
- return True
- except Exception as exc:
- logger.debug("Prefetch: operation status check failed for %s: %s", op_id, exc)
- return False
- return str(getattr(resp, "status", "") or "").lower() in {"completed", "failed"}
-
- def _wait_for_retains_drained(self, timeout: float) -> bool:
- """Block up to *timeout* s for the last retain to become recall-visible
- (prefetch thread only, never the reply path). Two barriers on one budget:
- (1) the writer queue drains — polls ``unfinished_tasks`` rather than
- ``queue.join()`` so a wedged write can't hang the prefetch; (2) the
- server-side async ops complete (async retain returns on acceptance, not
- durability). False on timeout/shutdown."""
- deadline = None if timeout <= 0 else time.monotonic() + timeout
- expired = lambda: deadline is not None and time.monotonic() >= deadline # noqa: E731
- while self._retain_queue.unfinished_tasks > 0:
- if self._shutting_down.is_set():
- return False
- if expired():
- logger.debug("Prefetch: retain drain timed out after %.1fs (%d pending)",
- timeout, self._retain_queue.unfinished_tasks)
- return False
- time.sleep(0.05)
- return self._wait_for_server_retain_ops(expired, timeout)
-
- def _wait_for_server_retain_ops(self, _expired: Callable[[], bool], timeout: float) -> bool:
- """Poll tracked async retain ops until complete or *_expired()* (deadline
- predicate). Ops still pending at the deadline are DROPPED: keeping them
- would let a permanently failing status endpoint burn the full timeout on
- EVERY later prefetch (a per-turn latency penalty via prefetch()'s bounded
- join). Trades a possibly-stale recall for liveness; WARNING once per prefetch."""
- while True:
- with self._pending_retain_ops_lock:
- bank_id = self._retain_ops_bank_id or self._bank_id
- pending = list(self._pending_retain_ops)
- if not pending:
- return True
- if self._shutting_down.is_set():
- return False
- done: set[str] = set()
- for op_id in pending:
- if self._shutting_down.is_set():
- return False
- if _expired():
- break
- if self._is_retain_op_complete(bank_id, op_id):
- done.add(op_id)
- with self._pending_retain_ops_lock:
- self._pending_retain_ops.difference_update(done)
- if not self._pending_retain_ops:
- return True
- dropped = len(self._pending_retain_ops) if _expired() else 0
- if dropped:
- self._pending_retain_ops.clear()
- if dropped:
- logger.warning("Prefetch: server retain visibility timed out after %.1fs; "
- "dropping %d unresolved op(s) so later prefetches stay "
- "bounded (recall may miss the just-completed turn)", timeout, dropped)
- return False
- time.sleep(self._RETAIN_OP_POLL_INTERVAL_S)
-
- # -- retain target -----------------------------------------------------------
-
- def _resolve_retain_target(self, fallback_document_id: str) -> tuple[str, str | None]:
- """(document_id, update_mode) from live API capability: >= 0.5.0 reuses the
- stable session-scoped id with ``update_mode='append'``; older APIs get
- *fallback_document_id* (per-process unique) and no update_mode — the only
- way the resume-overwrite fix works there. The /version probe targets the
- embedded client's dynamic per-profile port when running, else api_url.
-
- On Hindsight ≥ 0.5.0 the API supports ``update_mode='append'``, which lets us reuse a stable
- session-scoped ``document_id`` across process lifecycles without overwriting prior turns. On older
- APIs we fall back to *fallback_document_id* (the per-process unique ``f"{session_id}-{start_ts}"``
- minted at initialize / switch time) and don't pass ``update_mode`` at all — that's the only way the
- resume-overwrite fix (#6654) keeps working on legacy servers.
- """
- probe_url = self._api_url or ""
- if self._session_id and _check_api_supports_update_mode_append(probe_url, self._api_key):
- return self._session_id, "append"
- return fallback_document_id, None
-
- # -- lifecycle ---------------------------------------------------------------
-
- def initialize(self, session_id: str, **kwargs) -> None:
- self._session_id = str(session_id or "").strip()
- self._parent_session_id = str(kwargs.get("parent_session_id", "") or "").strip()
- # Status channel for the retain indicator (recall reports via recall_status()).
- if callable(kwargs.get("status_callback")):
- self._status_callback = kwargs["status_callback"]
- # Gated presentation for automatic startup warnings (agent._emit_warning on CLI).
- self._warning_callback = kwargs.get("warning_callback") if callable(kwargs.get("warning_callback")) else None
- self._platform = str(kwargs.get("platform") or "cli")
- # session_id stays in tags so processes for one session remain filterable together.
- self._document_id = _mint_document_id(self._session_id)
-
- self._config = cfg = _load_config()
- for name in _SESSION_KWARGS:
- setattr(self, f"_{name}", str(kwargs.get(name) or "").strip())
- self._turn_index = self._last_retained_turn_count = 0
- self._session_turns = []
- self._mode = cfg.get("mode", "cloud")
- self._timeout = self._int_setting("timeout", "HINDSIGHT_TIMEOUT", _DEFAULT_TIMEOUT)
- self._idle_timeout = self._int_setting("idle_timeout", "HINDSIGHT_IDLE_TIMEOUT", _DEFAULT_IDLE_TIMEOUT)
- if self._mode == "local": # legacy alias
- self._mode = "local_embedded"
- if self._mode == "local_embedded":
- available, reason = _check_local_runtime()
- if not available:
- logger.warning("Hindsight local mode disabled because its runtime could not be imported: %s.%s",
- reason, _local_runtime_hint(reason))
- self._mode = "disabled"
- return
- self._apply_connection_settings(cfg)
- self._apply_retain_settings(cfg)
- self._apply_recall_settings(cfg)
-
- client_version = "unknown"
- with contextlib.suppress(Exception):
- from importlib.metadata import version as pkg_version
- client_version = pkg_version("hindsight-client")
- logger.info("Hindsight initialized: mode=%s, api_url=%s, bank=%s, budget=%s, memory_mode=%s, prefetch_method=%s, client=%s",
- self._mode, self._api_url, self._bank_id, self._budget, self._memory_mode, self._prefetch_method, client_version)
- if self._bank_id_template:
- logger.debug("Hindsight bank resolved from template %r: profile=%s workspace=%s platform=%s user=%s -> bank=%s",
- self._bank_id_template, self._agent_identity, self._agent_workspace,
- self._platform, self._user_id, self._bank_id)
- logger.debug("Hindsight config: auto_retain=%s, auto_recall=%s, retain_every_n=%d, "
- "retain_async=%s, retain_context=%s, recall_max_tokens=%d, recall_max_input_chars=%d, tags=%s, recall_tags=%s",
- self._auto_retain, self._auto_recall, self._retain_every_n_turns,
- self._retain_async, self._retain_context, self._recall_max_tokens, self._recall_max_input_chars,
- self._tags, self._recall_tags)
-
- if self._mode == "local_embedded":
- self._start_embedded_daemon()
-
- def _apply_connection_settings(self, cfg: dict) -> None:
- """Endpoint, bank and mode selectors from *cfg* (env fallbacks where documented)."""
- self._api_key = _cloud_api_key(cfg)
- default_url = _DEFAULT_LOCAL_URL if self._mode in {"local_embedded", "local_external"} else _DEFAULT_API_URL
- self._api_url = cfg.get("api_url") or get_secret("HINDSIGHT_API_URL", "") or default_url
- self._llm_base_url = cfg.get("llm_base_url", "")
-
- banks = cfg_get(cfg, "banks", "hermes", default={})
- self._bank_id_template = cfg.get("bank_id_template", "") or ""
- self._bank_id = _resolve_bank_id_template(
- self._bank_id_template,
- fallback=cfg.get("bank_id") or banks.get("bankId", "hermes"),
- profile=self._agent_identity, workspace=self._agent_workspace,
- platform=self._platform, user=self._user_id, session=self._session_id,
- )
- budget = cfg.get("recall_budget") or cfg.get("budget") or banks.get("budget", "mid")
- self._budget = budget if budget in _VALID_BUDGETS else "mid"
- memory_mode = cfg.get("memory_mode", "hybrid")
- self._memory_mode = memory_mode if memory_mode in _SYSTEM_PROMPT_TAILS else "hybrid"
- prefetch_method = cfg.get("recall_prefetch_method") or cfg.get("prefetch_method", "recall")
- self._prefetch_method = prefetch_method if prefetch_method in {"recall", "reflect"} else "recall"
- self._bank_mission = cfg.get("bank_mission", "")
- self._bank_retain_mission = cfg.get("bank_retain_mission") or None
-
- def _apply_retain_settings(self, cfg: dict) -> None:
- def _cfg_or_env(key: str, env_var: str, default: str = "") -> Any:
- # The env half is the same per-profile value ``_load_config`` resolves through the scope;
- # a raw read here handed a multiplexed secondary the DEFAULT profile's retain shaping back.
- return cfg.get(key) or _scoped_setting(env_var, default)
-
- self._retain_tags = _normalize_retain_tags(_cfg_or_env("retain_tags", "HINDSIGHT_RETAIN_TAGS"))
- self._tags = self._retain_tags or None
- self._observation_scopes = _normalize_observation_scopes(
- _cfg_or_env("observation_scopes", "HINDSIGHT_RETAIN_OBSERVATION_SCOPES"))
- self._retain_source = str(_cfg_or_env("retain_source", "HINDSIGHT_RETAIN_SOURCE", _DEFAULT_RETAIN_SOURCE)).strip()
- self._retain_user_prefix = str(_cfg_or_env("retain_user_prefix", "HINDSIGHT_RETAIN_USER_PREFIX", "User")).strip() or "User"
- self._retain_assistant_prefix = (
- str(_cfg_or_env("retain_assistant_prefix", "HINDSIGHT_RETAIN_ASSISTANT_PREFIX", "Assistant")).strip()
- or "Assistant"
- )
- self._apply_retain_policy(cfg)
-
- def _apply_retain_policy(self, cfg: dict) -> None:
- """Pure-config retain knobs (no env/secret reads; ``{}`` yields the defaults)."""
- self._auto_retain = cfg.get("auto_retain", True)
- self._retain_every_n_turns = max(1, int(cfg.get("retain_every_n_turns", 1)))
- self._retain_context = cfg.get("retain_context", _RETAIN_CONTEXT_DEFAULT)
- self._retain_async = cfg.get("retain_async", True)
- # On by default so the user SEES memory working whether or not the model
- # mentions it; off switch for customer-facing agents (recall_indicator too).
- self._retain_indicator = bool(cfg.get("retain_indicator", True))
- # The next turn's warm prefetch could read BEFORE an async retain is
- # recall-visible; when True it first waits (bounded, off the reply path)
- # for the queue to drain AND the server-side op(s) to complete.
- self._prefetch_waits_for_retain = cfg.get("prefetch_waits_for_retain", True)
- self._prefetch_retain_drain_timeout = float(cfg.get("prefetch_retain_drain_timeout", 10.0))
-
- def _apply_recall_settings(self, cfg: dict) -> None:
- """Recall knobs are pure config too (``{}`` yields the defaults)."""
- self._recall_tags = cfg.get("recall_tags") or None
- self._recall_tags_match = cfg.get("recall_tags_match", "any")
- self._auto_recall = cfg.get("auto_recall", True)
- self._recall_sync = bool(cfg.get("recall_sync", False))
- self._recall_max_tokens = int(cfg.get("recall_max_tokens", 4096))
- self._recall_max_input_chars = int(cfg.get("recall_max_input_chars", 800))
- # None -> observation-only (Hindsight's consolidated, deduplicated layer; raw
- # world/experience facts re-ship the evidence they summarize and burn the
- # recall_max_tokens budget); a comma-separated string is accepted for parity
- # with recall_tags; an explicit list broadens or disables the filter.
- configured_types = cfg.get("recall_types")
- if isinstance(configured_types, str):
- self._recall_types = [t.strip() for t in configured_types.split(",") if t.strip()]
- else:
- self._recall_types = list([] if configured_types is None else configured_types) or ["observation"]
- self._recall_prompt_preamble = cfg.get("recall_prompt_preamble", "")
- self._recall_indicator = bool(cfg.get("recall_indicator", True))
-
- def _start_embedded_daemon(self) -> None:
- """Start the embedded daemon on a background thread (Rich output -> log file)."""
- # PostgreSQL's initdb refuses root; without this guard the start thread
- # retries forever, reloading embedding models (~958MB RAM, ~33% CPU)
- # with no user-visible error.
- if hasattr(os, "geteuid") and os.geteuid() == 0:
- msg = ("Hindsight local_embedded mode cannot run as root "
- "(PostgreSQL initdb refuses root). Skipping the embedded "
- "memory daemon. Run Hermes as a non-root user, or switch "
- "to cloud / local_external mode via 'hermes memory setup'.")
- logger.warning(msg)
- # Surface to the terminal too — a daemon that never starts would otherwise fail silently and
- # the user would only see Hermes get sluggish (issue #13125). This is an automatic
- # startup diagnostic: it goes through the agent's gated warning sink when wired,
- # otherwise through the shared render boundary; the log line above never does.
- with contextlib.suppress(Exception):
- cb = getattr(self, "_warning_callback", None)
- if cb is not None:
- cb(msg)
- else:
- from gateway.warning_notifications import render_notification
- render_notification(lambda: print(f" ⚠ {msg}", file=sys.stderr, flush=True),
- platform=getattr(self, "_platform", "cli"))
- self._mode = "disabled"
- return
- spawn_context_thread(self._daemon_start_worker, name="hindsight-daemon-start").start()
-
- def _daemon_start_worker(self) -> None:
- """Background daemon bring-up: ``_get_client`` syncs the profile .env, then
- starts/reuses the side-env daemon and connects the HTTP client."""
- try:
- self._get_client()
- logger.info("Hindsight embedded: daemon start worker finished (profile=%s)",
- self._config.get("profile", "hermes"))
- except Exception as e:
- logger.warning("Hindsight embedded daemon startup failed: %s", e, exc_info=True)
-
- def system_prompt_block(self) -> str:
- mode = self._memory_mode if self._memory_mode in _SYSTEM_PROMPT_TAILS else "hybrid"
- label = "" if mode == "hybrid" else f" ({mode} mode)"
- return f"# Hindsight Memory\nActive{label}. Bank: {self._bank_id}, budget: {self._budget}.\n{_SYSTEM_PROMPT_TAILS[mode]}"
-
- # -- recall ------------------------------------------------------------------
-
- def _recall_disabled(self) -> bool:
- """Guards shared by the async and synchronous recall paths."""
- why = ("tools-only mode" if self._memory_mode == "tools" else "auto_recall disabled" if not self._auto_recall
- else "shutting down" if self._shutting_down.is_set() else None)
- if why:
- logger.debug("Prefetch: skipped (%s)", why)
- return why is not None
-
- def _recall(self, query: str) -> list:
- kwargs: dict = {"bank_id": self._bank_id, "query": query, "budget": self._budget, "max_tokens": self._recall_max_tokens}
- if self._recall_tags:
- kwargs.update(tags=self._recall_tags, tags_match=self._recall_tags_match)
- if self._recall_types:
- kwargs["types"] = self._recall_types
- resp = self._run_hindsight_operation(lambda client: client.arecall(**kwargs))
- return resp.results or []
-
- def _reflect(self, query: str) -> str | None:
- resp = self._run_hindsight_operation(
- lambda client: client.areflect(bank_id=self._bank_id, query=query, budget=self._budget)
- )
- return resp.text
-
- def _do_recall(self, query: str) -> tuple[str, int]:
- """One recall/reflect for *query* (background prefetch and ``recall_sync`` paths)
- -> (text, memory count); the count is 0 for reflect (synthesis) and on error."""
- if self._recall_max_input_chars:
- query = query[:self._recall_max_input_chars]
- try:
- if self._prefetch_method == "reflect":
- logger.debug("Recall: calling reflect (bank=%s, query_len=%d)", self._bank_id, len(query))
- return self._reflect(query) or "", 0
- logger.debug("Recall: calling recall (bank=%s, query_len=%d, budget=%s)",
- self._bank_id, len(query), self._budget)
- results = self._recall(query)
- logger.debug("Recall: returned %d results", len(results))
- return "\n".join(f"- {r.text}" for r in results if r.text), len(results)
- except Exception as e:
- logger.debug("Hindsight recall failed: %s", e, exc_info=True)
- return "", 0
-
- def _finish_prefetch(self, result: str, count: int) -> str:
- """Record indicator state (cleared on empty turns, never a stale count); format the block."""
- self._last_recall_returned, self._last_recall_count = bool(result), count if result else 0
- if not result:
- logger.debug("Prefetch: no results available")
- return ""
- logger.debug("Prefetch: returning %d chars of context", len(result))
- header = self._recall_prompt_preamble or (
- "# Hindsight Memory (persistent cross-session context)\n"
- "Use this to answer questions about the user and prior sessions. "
- "Do not call tools to look up information that is already present here."
- )
- return f"{header}\n\n{result}"
-
- def _join_prefetch(self, timeout: float, *, log: bool = False) -> None:
- if not (self._prefetch_thread and self._prefetch_thread.is_alive()):
- return
- if log:
- logger.debug("Prefetch: waiting for background thread to complete")
- self._prefetch_thread.join(timeout=timeout)
-
- def prefetch(self, query: str, *, session_id: str = "") -> str:
- # Opt-in: recall synchronously against the *current* message so the
- # injected memories match this turn's query, not the previous turn's.
- # See NousResearch/hermes-agent#5820.
- if self._recall_sync:
- return self._finish_prefetch(*(("", 0) if self._recall_disabled() else self._do_recall(query)))
- # Default: the background worker's result for the previous turn (capped join).
- self._join_prefetch(3.0, log=True)
- with self._prefetch_lock:
- result, count = self._prefetch_result, self._prefetch_count
- self._prefetch_result, self._prefetch_count = "", 0
- return self._finish_prefetch(result, count)
-
- def recall_status(self) -> Optional[RecallStatus]:
- """Count injected by the last prefetch; None if nothing injected or ``recall_indicator=false``."""
- if not self._recall_indicator or not self._last_recall_returned:
- return None
- return RecallStatus(provider_label="Hindsight", count=self._last_recall_count, glyph=_HINDSIGHT_GLYPH)
-
- def queue_prefetch(self, query: str, *, session_id: str = "") -> None:
- # Sync mode recalls live each turn — nothing to prime in the background.
- if self._recall_sync or self._recall_disabled():
- return
-
- def _run():
- # Wait (bounded, off the reply path) for the just-completed turn's
- # retain to be recall-visible so the warmed context includes it.
- if self._prefetch_waits_for_retain:
- self._wait_for_retains_drained(self._prefetch_retain_drain_timeout)
- text, count = self._do_recall(query)
- if text:
- with self._prefetch_lock:
- self._prefetch_result, self._prefetch_count = text, count
-
- self._prefetch_thread = spawn_context_thread(_run, name="hindsight-prefetch")
- self._prefetch_thread.start()
-
- # -- retain ------------------------------------------------------------------
-
- def _build_turn_messages(self, user_content: str, assistant_content: str) -> List[Dict[str, str]]:
- now = _event_timestamp() # one turn -> both messages share the event timestamp
- return [{"role": role, "content": f"{prefix}: {content}", "timestamp": now} for role, prefix, content in
- (("user", self._retain_user_prefix, user_content), ("assistant", self._retain_assistant_prefix, assistant_content))]
-
- def _build_metadata(self, *, message_count: int, turn_index: int) -> Dict[str, str]:
- metadata: Dict[str, str] = {
- # UTC write/audit time (event time lives on the item timestamp).
- "retained_at": datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z"),
- "message_count": str(message_count),
- "turn_index": str(turn_index),
- }
- if self._retain_source:
- metadata["source"] = self._retain_source
- metadata.update({name: value for name in _METADATA_ATTRS if (value := getattr(self, f"_{name}"))})
- return metadata
-
- def _build_retain_kwargs(self, content: str, *, context: str | None = None,
- metadata: Dict[str, str] | None = None, tags: List[str] | None = None,
- occurred_at: str | None = None, update_mode: str | None = None) -> Dict[str, Any]:
- """Build one aretain_batch item. The server resolves occurred_start/end (incl.
- relative phrases in content) from the item timestamp: explicit occurred_at
- wins, else the configured event clock."""
- item: Dict[str, Any] = {
- # See #93568.
- "content": content,
- "metadata": metadata or self._build_metadata(message_count=1, turn_index=self._turn_index),
- "timestamp": (occurred_at or "").strip() or _event_timestamp(),
- }
- merged_tags = _normalize_retain_tags(list(self._retain_tags) + _normalize_retain_tags(tags))
- item.update({k: v for k, v in (("context", context), ("update_mode", update_mode)) if v is not None})
- item.update({k: v for k, v in (("tags", merged_tags), ("observation_scopes", self._observation_scopes)) if v})
- return item
-
- def _retain_batch(self, item: dict, *, bank_id: str, document_id: str | None = None,
- retain_async: bool | None = None):
- """Dispatch one item via aretain_batch (bank_id/document_id/retain_async are
- call-level args, never item keys)."""
- kwargs: Dict[str, Any] = {"bank_id": bank_id, "items": [item], "document_id": document_id, "retain_async": retain_async}
- kwargs = {k: v for k, v in kwargs.items() if v is not None}
- return self._run_hindsight_operation(lambda client: client.aretain_batch(**kwargs))
-
- def _make_turn_retain_job(self, turns: list[str], *, document_id: str, update_mode: str | None,
- label: str, track_ops: bool = True) -> Callable[[], None]:
- """Writer job shipping *turns* as one document. Inputs are snapshotted NOW: the
- writer runs after later sync_turn() calls mutate _session_turns/_turn_index/_session_id."""
- content = "[" + ",".join(turns) + "]"
- metadata = self._build_metadata(message_count=len(turns) * 2, turn_index=self._turn_index)
- lineage = (("session", self._session_id), ("parent", self._parent_session_id))
- tags = [f"{kind}:{sid}" for kind, sid in lineage if sid] or None
- bank_id, retain_async, retain_context = self._bank_id, self._retain_async, self._retain_context
-
- def _job() -> None:
- item = self._build_retain_kwargs(content, context=retain_context, metadata=metadata,
- tags=tags, update_mode=update_mode)
- logger.debug("Hindsight %s: bank=%s, doc=%s, mode=%s, async=%s, content_len=%d, num_turns=%d",
- label, bank_id, document_id, update_mode, retain_async, len(content), len(turns))
- resp = self._retain_batch(item, bank_id=bank_id, document_id=document_id, retain_async=retain_async)
- # Async retains are only *accepted* here; track the op id(s) so the
- # next-turn prefetch can wait for true server-side completion.
- if retain_async and track_ops:
- self._track_retain_ops(resp, bank_id)
- logger.debug("Hindsight %s succeeded", label)
-
- return _job
-
- def sync_turn(self, user_content: str, assistant_content: str, *, session_id: str = "") -> None:
- """Enqueue a retain for the current turn (non-blocking; writer thread). Dropped
- once shutdown() fired so post-exit retains never reach aiohttp during teardown."""
- why = "auto_retain disabled" if not self._auto_retain else "shutting down" if self._shutting_down.is_set() else None
- if why:
- logger.debug("sync_turn: skipped (%s)", why)
- return
- if session_id:
- self._session_id = str(session_id).strip()
-
- self._session_turns.append(json.dumps(self._build_turn_messages(user_content, assistant_content), ensure_ascii=False))
- self._turn_counter = self._turn_index = self._turn_counter + 1
- if remainder := self._turn_counter % self._retain_every_n_turns:
- logger.debug("sync_turn: buffered turn %d (will retain at turn %d)",
- self._turn_counter, self._turn_counter + (self._retain_every_n_turns - remainder))
- return
-
- document_id, update_mode = self._resolve_retain_target(self._document_id)
- # Append-capable APIs get only the delta since the last retain; legacy /
- # overwrite APIs need the whole session because each retain replaces the document.
- start = self._last_retained_turn_count if update_mode == "append" else 0
- turns_to_retain = self._session_turns[start:]
- if not turns_to_retain:
- logger.debug("sync_turn: skipped append retain; no new turns since last retain")
- return
- logger.debug("sync_turn: retaining %d/%d turns, payload %d chars",
- len(turns_to_retain), len(self._session_turns), sum(len(t) for t in turns_to_retain))
-
- job = self._make_turn_retain_job(turns_to_retain, document_id=document_id,
- update_mode=update_mode, label="retain")
- # Indicator fires only past every skip/buffer gate: solely on turns that persist.
- # Model-independent status line; no-op without retain_indicator/status channel.
- if self._retain_indicator and self._status_callback is not None:
- try:
- self._status_callback(f"{_HINDSIGHT_GLYPH} Hindsight — saving to memory…")
- except Exception:
- logger.debug("Retain indicator emit failed (non-fatal)", exc_info=True)
- self._enqueue_retain(job)
- # Advance the watermark only after the delta is queued so a later retain
- # doesn't re-ship turns already handed to the writer.
- if update_mode == "append":
- # The job above holds its own copy, and append retains (here and flush-on-switch) only
- # ever read the un-retained tail — so drop shipped turns instead of pinning every turn
- # of a never-ending session (#62950). Overwrite mode resends the whole session and
- # must keep them all.
- self._session_turns.clear()
- self._last_retained_turn_count = 0
-
- def _enqueue_retain(self, job: Callable[[], None]) -> None:
- """Hand *job* to the (lazily started) writer and arm the atexit drain."""
- self._ensure_writer()
- self._register_atexit()
- self._retain_queue.put(job)
-
- # -- tools -------------------------------------------------------------------
-
- def get_tool_schemas(self) -> List[Dict[str, Any]]:
- return [] if self._memory_mode == "context" else [RETAIN_SCHEMA, RECALL_SCHEMA, REFLECT_SCHEMA]
-
- def _tool_retain(self, args: dict) -> str:
- content, context = args["content"], args.get("context")
- item = self._build_retain_kwargs(content, context=context, tags=args.get("tags"),
- occurred_at=args.get("occurred_at"))
- logger.debug("Tool hindsight_retain: bank=%s, content_len=%d, context=%s",
- self._bank_id, len(content), context)
- self._retain_batch(item, bank_id=self._bank_id)
- logger.debug("Tool hindsight_retain: success")
- return "Memory stored successfully."
-
- def _tool_recall(self, args: dict) -> str:
- query = args["query"]
- logger.debug("Tool hindsight_recall: bank=%s, query_len=%d, budget=%s",
- self._bank_id, len(query), self._budget)
- results = self._recall(query)
- logger.debug("Tool hindsight_recall: %d results", len(results))
- return "\n".join(f"{i}. {r.text}" for i, r in enumerate(results, 1)) or "No relevant memories found."
-
- def _tool_reflect(self, args: dict) -> str:
- query = args["query"]
- logger.debug("Tool hindsight_reflect: bank=%s, query_len=%d, budget=%s",
- self._bank_id, len(query), self._budget)
- text = self._reflect(query) or ""
- logger.debug("Tool hindsight_reflect: response_len=%d", len(text))
- return text or "No relevant memories found."
-
- # tool name -> (required arg, handler, user-facing failure prefix)
- _TOOL_HANDLERS = {
- "hindsight_retain": ("content", _tool_retain, "Failed to store memory"),
- "hindsight_recall": ("query", _tool_recall, "Failed to search memory"),
- "hindsight_reflect": ("query", _tool_reflect, "Failed to reflect"),
- }
-
- def handle_tool_call(self, tool_name: str, args: dict, **kwargs) -> str:
- if tool_name not in self._TOOL_HANDLERS:
- return tool_error(f"Unknown tool: {tool_name}")
- required, handler, failure = self._TOOL_HANDLERS[tool_name]
- if not args.get(required, ""):
- return tool_error(f"Missing required parameter: {required}")
- try:
- return json.dumps({"result": handler(self, args)})
- except Exception as e:
- logger.warning("%s failed: %s", tool_name, e, exc_info=True)
- return tool_error(f"{failure}: {e}")
-
- # -- session lifecycle -------------------------------------------------------
-
- def on_session_switch(self, new_session_id: str, *, parent_session_id: str = "",
- reset: bool = False, **kwargs) -> None:
- """Rotate per-session state (/resume, /branch, /reset, /new, compression) so
- writes don't land in the previous session's document. Always: flush buffered
- turns under the OLD ids first (``retain_every_n_turns > 1`` would silently
- lose them), join the in-flight prefetch and drop its result (no stale recall
- for the new session), then set ``_session_id``, mint a fresh ``_document_id``
- and clear the batch buffers. ``reset`` is accepted but unneeded: buffer
- clearing is correct for every switch.
-
- Without this hook, initialize()-cached state (``_session_id``, ``_document_id``, ``_session_turns``,
- ``_turn_counter``) would keep pointing at the previous session and writes would land in the wrong
- document. See hermes-agent#6672.
- Always update ``_session_id`` so metadata and tags on subsequent retains reflect the active session.
- Always clear the accumulated batch buffers (``_session_turns``, ``_turn_counter``, ``_turn_index``)
- — even for /resume and /branch, the new session's batching must start from zero so an in-flight
- retain doesn't flush under the wrong ``_document_id``. See #1303.
- """
- new_id = str(new_session_id or "").strip()
- if not new_id:
- return
-
- # 1. Flush buffered turns under the OLD identifiers, resolved BEFORE the
- # rotation (legacy: per-process unique; >=0.5.0: session-scoped + append).
- if self._session_turns:
- old_document_id, old_update_mode = self._resolve_retain_target(self._document_id)
- job = self._make_turn_retain_job(list(self._session_turns), document_id=old_document_id,
- update_mode=old_update_mode, label="flush-on-switch",
- track_ops=False)
-
- def _flush():
- try:
- job()
- except Exception as e:
- logger.warning("Hindsight flush-on-switch failed: %s", e, exc_info=True)
- # Same writer queue as sync_turn: FIFO behind queued old-session retains,
- # no two threads racing aretain_batch on one document, shutdown drain intact.
- if not self._shutting_down.is_set():
- self._enqueue_retain(_flush)
-
- # 2. Drain the old session's in-flight prefetch and drop its result.
- self._join_prefetch(3.0)
- with self._prefetch_lock:
- self._prefetch_result = ""
-
- # 3. Rotate to the new session.
- if parent_session_id:
- self._parent_session_id = str(parent_session_id).strip()
- self._session_id, self._document_id = new_id, _mint_document_id(new_id)
- self._session_turns = []
- self._turn_counter = self._turn_index = self._last_retained_turn_count = 0
- logger.debug("Hindsight on_session_switch: new_session=%s parent=%s reset=%s doc=%s",
- self._session_id, self._parent_session_id, reset, self._document_id)
-
- def _close_client(self) -> None:
- # Both modes hold a hindsight_client.Hindsight (embedded talks HTTP to the
- # side-env daemon): close on the shared loop.
- self._run_sync(self._client.aclose())
-
- def shutdown(self) -> None:
- logger.debug("Hindsight shutdown: stopping writer + waiting for background threads")
- # Stop accepting retain jobs first so late sync_turn() calls are dropped.
- self._shutting_down.set()
- # The writer finishes in-flight work then exits on the sentinel; the
- # bounded join keeps shutdown predictable even if the daemon is wedged.
- if (writer := self._writer_thread) is not None and writer.is_alive():
- self._retain_queue.put(_WRITER_SENTINEL)
- writer.join(timeout=10.0)
- if writer.is_alive():
- logger.warning("Hindsight writer did not stop within 10s; abandoning %d pending retain(s)",
- self._retain_queue.qsize())
- self._join_prefetch(5.0)
- if self._client is not None:
- with contextlib.suppress(Exception):
- self._close_client()
- self._client = None
- # The module-global loop is intentionally NOT stopped: it's shared by every
- # provider in the process (one per gateway chat session); stopping it would
- # strand siblings' aiohttp sessions ("Unclosed client session"). Daemon
- # thread, reclaimed at process exit.
-
-
-# The module-global background event loop (_loop / _loop_thread) is intentionally NOT stopped here. It is
-# shared across every HindsightMemoryProvider instance in the process — the plugin loader creates a new
-# provider per AIAgent, and the gateway creates one AIAgent per concurrent chat session. Stopping the loop
-# from one provider's shutdown() strands the aiohttp ClientSession + TCPConnector owned by every sibling
-# provider on a dead loop, which surfaces as the "Unclosed client session" / "Unclosed connector" warnings
-# reported in #11923. The loop runs on a daemon thread and is reclaimed on process exit; per-session cleanup
-# happens via self._client.aclose() above.
-def register(ctx) -> None:
- """Register Hindsight as a memory provider plugin."""
- ctx.register_memory_provider(HindsightMemoryProvider())
-
-
-# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
-# Names external plugins imported from this module before the Sep 2026 decomposition.
-# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).
-# The whole block is removed by reverting the commit that added it.
-from dataclasses import dataclass # noqa: F401,E402
-import importlib # noqa: F401,E402
-# ---- END PLUGIN-COMPAT ----
diff --git a/plugins/memory/hindsight/config_schema.py b/plugins/memory/hindsight/config_schema.py
deleted file mode 100644
index 4a2f1dbf242..00000000000
--- a/plugins/memory/hindsight/config_schema.py
+++ /dev/null
@@ -1,36 +0,0 @@
-"""Hindsight's declared config surface — rendered by the generic desktop panel."""
-
-from plugins.memory.config_schema import (
- KIND_SECRET, KIND_SELECT, KIND_TEXT, ProviderConfigSchema, ProviderField, ProviderFieldOption,
-)
-
-CONFIG_SCHEMA = ProviderConfigSchema(
- name="hindsight",
- label="Hindsight",
- fields=(
- ProviderField(
- key="mode", label="Mode", kind=KIND_SELECT, default="cloud",
- description="How Hermes connects to Hindsight.",
- options=(
- ProviderFieldOption("cloud", "Cloud", "Hindsight Cloud API (lightweight, just needs an API key)"),
- ProviderFieldOption("local_external", "Local External", "Connect to an existing Hindsight instance"),
- ),
- inline=True,
- ),
- ProviderField(
- key="api_key", label="API key", kind=KIND_SECRET, env_key="HINDSIGHT_API_KEY",
- description="Used to authenticate with the Hindsight API.",
- placeholder="Enter Hindsight API key", inline=True,
- ),
- ProviderField(
- key="api_url", label="API URL", kind=KIND_TEXT, default="https://api.hindsight.vectorize.io",
- aliases=("apiUrl",), env_fallbacks=("HINDSIGHT_API_URL",), inline=True,
- ),
- ProviderField(key="bank_id", label="Bank ID", kind=KIND_TEXT, default="hermes", aliases=("bankId",), inline=True),
- ProviderField(
- key="recall_budget", label="Recall budget", kind=KIND_SELECT, default="mid", aliases=("budget",),
- options=tuple(ProviderFieldOption(b, b) for b in ("low", "mid", "high")),
- inline=True,
- ),
- ),
-)
diff --git a/plugins/memory/hindsight/embedded.py b/plugins/memory/hindsight/embedded.py
deleted file mode 100644
index 8aa68635f50..00000000000
--- a/plugins/memory/hindsight/embedded.py
+++ /dev/null
@@ -1,188 +0,0 @@
-"""Local-embedded Hindsight runtime seam: side-env runtime probe, install hint, and
-the per-profile env file the standalone ``hindsight-embed`` daemon consumes. The
-heavy stack itself lives in the isolated side env owned by ``embedded_runtime`` —
-nothing here imports it in-process."""
-
-from __future__ import annotations
-
-import contextlib
-import os
-from pathlib import Path
-from typing import Any
-
-from agent.secret_scope import UnscopedSecretError, get_secret
-
-from .settings import _DEFAULT_IDLE_TIMEOUT, _daemon_llm_provider, _parse_int_setting
-
-# Stale embedded-daemon connection markers (client recreated, operation retried once).
-_RETRIABLE_CONNECTION_MARKERS = (
- "cannot connect to host",
- # Connection-establishment / DNS failure message patterns. These surface when the exception TYPE is
- # generic (RuntimeError/Exception from a local shim, MCP bridge, subprocess wrapper, or an SDK that
- # re-raises without chaining) so the _TRANSPORT_ERROR_TYPES check never fires, and the error carries no
- # HTTP status. Without message-level matching they fall through to FailoverReason.unknown, which misses
- # the transport eager-fallback path in the retry loop (unknown retries the same dead endpoint for the
- # full budget before fallback). Ported from anomalyco/opencode#40707, which hit the same bug shape:
- # serialized midstream errors matched by type only. Deliberately EXCLUDES mid-stream disconnect strings
- # ("connection reset by peer", "peer closed connection", "unexpected eof", "socket hang up") — those
- # belong to _SERVER_DISCONNECT_PATTERNS, whose classification step runs later and routes large sessions
- # to context-overflow compression. A connection that was never established cannot be a server-side
- # overflow rejection, so these are safe to classify as plain retryable transport.
- "connection refused",
- "connect call failed",
- "clientconnectorerror",
-)
-
-
-def _check_local_runtime() -> tuple[bool, str | None]:
- """Whether the isolated side-env runtime imports cleanly (probed in the side
- interpreter — older CPUs: NumPy can raise at import, so Hermes degrades
- instead of retrying a broken backend; ``sentence_transformers`` is probed
- too: ``hindsight`` imports fine with a broken embedding stack, and the
- daemon would then abort on every retain/recall)."""
- from .embedded_runtime import check_local_runtime
-
- return check_local_runtime()
-
-
-def _local_runtime_hint(reason: str | None) -> str:
- """Install/reinstall guidance when the local_embedded side runtime is missing
- or broken (probe reason appended when present)."""
- from .embedded_runtime import _local_runtime_hint as _hint
-
- return _hint(reason)
-
-
-def _load_simple_env(path) -> dict[str, str]:
- """Parse a KEY=VALUE env file (comments/blank lines ignored). utf-8-sig: also used
- on the Hermes .env during post_setup, where a Notepad BOM would stick to the first key."""
- if not path.exists():
- return {}
- pairs = (line.split("=", 1) for line in path.read_text(encoding="utf-8-sig", errors="replace").splitlines()
- if line and not line.startswith("#") and "=" in line)
- return {key.strip(): value.strip() for key, value in pairs}
-
-
-def _embedded_profile_env_path(config: dict[str, Any]) -> Path:
- profile = str(config.get("profile", "hermes") or "hermes")
- return Path.home() / ".hindsight" / "profiles" / f"{profile}.env"
-
-
-def _on_disk_llm_api_key(config: dict[str, Any]) -> str:
- """The key currently persisted in the profile env file ("" when absent)."""
- with contextlib.suppress(Exception):
- return _load_simple_env(_embedded_profile_env_path(config)).get("HINDSIGHT_API_LLM_API_KEY", "") or ""
- return ""
-
-
-def _embedded_llm_api_key(config: dict[str, Any]) -> str:
- """Resolve the LLM API key: explicit config first, then the profile secret
- scope, then the on-disk profile env as a last resort.
-
- The disk fallback is the durability core: the background daemon-start
- worker usually runs with no secret scope, and without it the client would
- be built keyless — its ``ensure_running(config)`` merge would then
- overwrite the file's good key with emptiness inside the upstream manager
- (``_register_profile`` → ``create_profile`` rewrite). Falling back to the
- persisted key keeps the in-process client, the file compare, and the
- daemon subprocess all keyed from the same surviving copy.
- """
- if config.get("llmApiKey") or config.get("llm_api_key"):
- return config.get("llmApiKey") or config.get("llm_api_key")
- # NOTE: the vault item is named HINDSIGHT_API_LLM_API_KEY (matching the
- # daemon's env var), not HINDSIGHT_LLM_API_KEY (the setup-wizard name).
- # Accept both so vault-fed scopes resolve regardless of which name the
- # secret source carries.
- try:
- scoped = get_secret("HINDSIGHT_API_LLM_API_KEY", "") or get_secret("HINDSIGHT_LLM_API_KEY", "")
- except UnscopedSecretError:
- # Multiplexed gateway with no profile scope on this thread: never let
- # a missing scope read os.environ (another profile's key may live
- # there). Fall through to the on-disk copy below.
- scoped = ""
- if scoped:
- return scoped
- return _on_disk_llm_api_key(config)
-
-
-def _may_rewrite_profile_env(config: dict[str, Any]) -> bool:
- """Whether rewriting the profile env file is safe right now.
-
- False exactly when the build has no key (no scope, no config key) but the
- file holds one: a rewrite would clobber live credentials with emptiness.
- All other mismatches (model/provider/base-url/idle-timeout drift, missing
- file, key rotation to a new non-empty value) remain writable.
- """
- if _build_embedded_profile_env(config).get("HINDSIGHT_API_LLM_API_KEY"):
- return True
- return not _on_disk_llm_api_key(config)
-
-
-def _build_embedded_profile_env(config: dict[str, Any], *, llm_api_key: str | None = None) -> dict[str, str]:
- """Build the profile-scoped env that standalone hindsight-embed consumes."""
- if llm_api_key is None:
- llm_api_key = _embedded_llm_api_key(config)
- env_values = {
- "HINDSIGHT_API_LLM_PROVIDER": str(_daemon_llm_provider(config.get("llm_provider", ""))),
- "HINDSIGHT_API_LLM_API_KEY": str(llm_api_key or ""),
- "HINDSIGHT_API_LLM_MODEL": str(config.get("llm_model", "")),
- "HINDSIGHT_API_LOG_LEVEL": "info",
- }
- # Base URL is per-profile like the key beside it (the scoped key must not go to the default's host);
- # on the scopeless daemon worker a miss is a miss, never os.environ (same rule as the key above).
- base_url = config.get("llm_base_url")
- if not base_url:
- try:
- base_url = get_secret("HINDSIGHT_API_LLM_BASE_URL", "") or ""
- except UnscopedSecretError:
- base_url = ""
- if base_url:
- env_values["HINDSIGHT_API_LLM_BASE_URL"] = str(base_url)
- if (idle_timeout := config.get("idle_timeout")) is None:
- idle_timeout = os.environ.get("HINDSIGHT_IDLE_TIMEOUT")
- if idle_timeout is not None and idle_timeout != "":
- env_values["HINDSIGHT_EMBED_DAEMON_IDLE_TIMEOUT"] = str(_parse_int_setting(idle_timeout, _DEFAULT_IDLE_TIMEOUT))
- return env_values
-
-
-def _secure_write_profile_env(profile_env: Path, content: str) -> None:
- """Create/overwrite *profile_env* owner-only (0600); a pre-existing file is
- tightened BEFORE the plaintext LLM API key is written."""
- if profile_env.exists():
- with contextlib.suppress(OSError):
- os.chmod(profile_env, 0o600)
- fd = os.open(str(profile_env), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
- with os.fdopen(fd, "w", encoding="utf-8") as fh:
- fh.write(content)
-
-
-def _validate_profile_env_permissions(profile_env: Path) -> None:
- """Post-write check: owner-only on POSIX (Windows ACLs aren't mode bits; skipped)."""
- if os.name != "posix":
- return
- import stat
-
- if stat.S_IMODE(profile_env.stat().st_mode) != 0o600:
- with contextlib.suppress(OSError):
- os.chmod(profile_env, 0o600)
- if stat.S_IMODE(profile_env.stat().st_mode) != 0o600:
- raise PermissionError(
- f"Embedded Hindsight profile environment is not owner-only: {profile_env}"
- )
-
-
-def _materialize_embedded_profile_env(config: dict[str, Any], *, llm_api_key: str | None = None) -> Path:
- """Write the profile env file; never leave a plaintext key in a file whose
- permissions could not be verified."""
- profile_env = _embedded_profile_env_path(config)
- profile_env.parent.mkdir(parents=True, exist_ok=True)
- env_values = _build_embedded_profile_env(config, llm_api_key=llm_api_key)
- content = "".join(f"{key}={value}\n" for key, value in env_values.items())
- try:
- _secure_write_profile_env(profile_env, content)
- _validate_profile_env_permissions(profile_env)
- except BaseException:
- with contextlib.suppress(OSError):
- profile_env.unlink()
- raise
- return profile_env
diff --git a/plugins/memory/hindsight/embedded_runtime.py b/plugins/memory/hindsight/embedded_runtime.py
deleted file mode 100644
index f186fabf4c4..00000000000
--- a/plugins/memory/hindsight/embedded_runtime.py
+++ /dev/null
@@ -1,223 +0,0 @@
-"""Build an isolated Hindsight API runtime and start its daemon in that interpreter."""
-
-from __future__ import annotations
-
-import json
-import logging
-import os
-import subprocess
-from pathlib import Path
-from typing import Any
-
-from hermes_constants import get_hermes_home
-
-logger = logging.getLogger(__name__)
-
-_EMBED_VERSION = "0.9.2"
-_API_SLIM_VERSION = "0.9.2"
-_REQUIREMENTS = (f"hindsight-embed=={_EMBED_VERSION}", f"hindsight-api-slim[all]=={_API_SLIM_VERSION}")
-
-# First successful daemon start downloads/loads ML models — minutes, not seconds.
-_DEFAULT_DAEMON_START_TIMEOUT = 900.0
-_INSTALL_TIMEOUT = 3600
-_PROBE_TIMEOUT = 300.0
-
-_PORT_HEALTH_GRACE_ENV = "HINDSIGHT_EMBED_PORT_HEALTH_GRACE_TIMEOUT"
-_API_VERSION_ENV = "HINDSIGHT_EMBED_API_VERSION"
-
-# Printed by the bridge as its LAST stdout line; the manager's Rich output and
-# the daemon's own logs share the stream, so the marker makes parsing exact.
-_BRIDGE_MARKER = "__HERMES_HINDSIGHT_BRIDGE__"
-
-_PROBE_CODE = "import hindsight_embed.daemon_embed_manager, hindsight_api, sentence_transformers"
-
-_DAEMON_BRIDGE_CODE = """\
-import json, sys
-from hindsight_embed import daemon_client
-
-profile = sys.argv[1]
-if len(sys.argv) > 2 and sys.argv[2] == "restart":
- daemon_client.stop_daemon(profile)
-result = {"ok": False, "url": None, "error": None}
-try:
- # {} config: the manager merges the profile's own .env (materialized by the
- # plugin) over it, so the LLM keys live only in the 0600 profile file.
- result["ok"] = bool(daemon_client.ensure_daemon_running({}, profile))
- if result["ok"]:
- result["url"] = daemon_client.get_daemon_url(profile)
- else:
- result["error"] = "daemon did not start (see the hindsight profile log)"
-except Exception as exc: # bridge must always report, never crash the parse
- result["error"] = f"{type(exc).__name__}: {exc}"
-print("@MARKER@" + json.dumps(result))
-""".replace("@MARKER@", _BRIDGE_MARKER)
-
-
-def sideenv_root() -> Path:
- """Private side env for the embedded runtime (never the boot-selected venv)."""
- return get_hermes_home() / "profiles" / "Hindsight" / "env"
-
-
-def sideenv_python(root: Path | None = None) -> Path | None:
- """Read PM's selected side interpreter without creating an environment."""
- import pm
-
- return pm.environment_python("hindsight", root=root if root is not None else sideenv_root())
-
-
-def ensure_sideenv() -> Path:
- """Provision the isolated embedded runtime; PM owns generation publication."""
- import pm
-
- return pm.ensure_environment(
- "hindsight", _REQUIREMENTS, root=sideenv_root(), explicit=True, timeout=_INSTALL_TIMEOUT,
- )
-
-
-def _probe_interpreter(python: Path, timeout: float = _PROBE_TIMEOUT) -> tuple[bool, str | None]:
- """Import the embedded stack IN THE SIDE ENV (its own interpreter). Covers the
- old-CPU NumPy failure class and a broken embedding stack the same way the
- legacy in-process probe did — but inside the isolated environment."""
- try:
- result = subprocess.run( # noqa: S603 — fixed argv, no shell
- [str(python), "-c", _PROBE_CODE], capture_output=True, text=True,
- encoding="utf-8", errors="replace", timeout=timeout,
- env=_daemon_subprocess_env({}),
- )
- except (OSError, subprocess.TimeoutExpired) as exc:
- return False, f"side runtime probe failed: {exc}"
- if result.returncode == 0:
- return True, None
- reason = (result.stderr or result.stdout or "").strip()
- return False, reason[-500:] if reason else f"probe exited {result.returncode}"
-
-
-#: Probe verdict per side interpreter, for this process. The probe imports torch via
-#: sentence_transformers — seconds of cold start — and is_available() /
-#: unavailable_reason() / initialize() each ask it per session. A reinstall publishes a new
-#: PM generation (a different interpreter path), so the key misses and the env is re-probed.
-_probe_verdicts: dict[Path, tuple[bool, str | None]] = {}
-
-
-def check_local_runtime() -> tuple[bool, str | None]:
- """(available, reason) for local_embedded — probes the side env, never the
- boot-selected main environment."""
- root = sideenv_root()
- python = sideenv_python(root)
- if python is None:
- reason = (f"the isolated Hindsight runtime is not installed at {root}; "
- "run 'hermes memory setup' and choose Local Embedded")
- logger.debug("Hindsight local runtime unavailable: %s", reason)
- return False, reason
- verdict = _probe_verdicts.get(python)
- if verdict is None:
- verdict = _probe_verdicts[python] = _probe_interpreter(python)
- available, reason = verdict
- if available:
- logger.debug("Hindsight side runtime probe OK (%s)", python)
- else:
- logger.debug("Hindsight side runtime probe failed: %s", reason)
- return available, reason
-
-
-def _local_runtime_hint(reason: str | None) -> str:
- """Install/reinstall guidance for an unavailable side runtime. The main
- Hermes environment is never touched, so the fix is always the same one."""
- text = f"{reason or ''}".strip()
- return (
- " The local_embedded runtime lives in an isolated environment"
- f" ({sideenv_root()}; hindsight-embed=={_EMBED_VERSION} +"
- f" hindsight-api-slim[all]=={_API_SLIM_VERSION}), separate from Hermes"
- " itself. Reinstall it with 'hermes memory setup' (Local Embedded), or"
- " switch to cloud / local_external mode."
- + (f" Last probe failure: {text}" if text else "")
- )
-
-
-def _daemon_subprocess_env(config: dict[str, Any]) -> dict[str, str]:
- """Env for the side-env bridge/manager process. daemon_embed_manager reads
- the health-grace window AT IMPORT TIME of that process, so it rides here —
- not in Hermes' own environment. Main-env interpreter markers are stripped so
- the side python resolves only its own environment.
-
- Built for the SERVED profile, never ``dict(os.environ)``: under multiplex the
- process env is the launch profile's, so profile X's daemon would have started
- with the default profile's HERMES_HOME and credentials. Credentials are not
- inherited at all — the manager reads the LLM keys from the profile's own 0600
- env file (see the bridge), so the child needs none from us."""
- from tools.environments.local import served_profile_child_env
-
- env = served_profile_child_env(inherit_credentials=False)
- env["PYTHONUTF8"] = "1"
- for key in ("VIRTUAL_ENV", "PYTHONPATH", "PYTHONHOME", "PYTHONSTARTUP", "PYTHONEXECUTABLE"):
- env.pop(key, None)
- raw = config.get("port_health_grace_timeout")
- if raw not in (None, ""):
- try:
- seconds = float(raw)
- except (TypeError, ValueError):
- logger.warning("Invalid Hindsight port_health_grace_timeout %r; ignoring.", raw)
- else:
- if seconds >= 0:
- env.setdefault(_PORT_HEALTH_GRACE_ENV, repr(seconds))
- else:
- logger.warning("Negative Hindsight port_health_grace_timeout %r; ignoring.", raw)
- # Freeze the daemon/API component version to the pinned pair (the manager
- # reads this as the profile .env override's fallback).
- env[_API_VERSION_ENV] = _API_SLIM_VERSION
- return env
-
-
-def _parse_bridge_output(stdout: str) -> dict[str, Any]:
- """The bridge's marked JSON line; Rich/log noise is ignored."""
- for line in reversed(stdout.splitlines()):
- if line.startswith(_BRIDGE_MARKER):
- try:
- return json.loads(line[len(_BRIDGE_MARKER):])
- except ValueError:
- continue
- return {}
-
-
-def ensure_daemon_and_url(config: dict[str, Any], *, restart: bool = False) -> str:
- """Start (or reuse) the side-env daemon and return its URL.
-
- The URL is resolved by the side env's own ProfileManager/get_url — profile
- ``HINDSIGHT_API_PORT`` override, then the manager's metadata allocation —
- and never hardcoded here. The daemon child runs the side env's hindsight-api
- because DaemonEmbedManager resolves the API command from the interpreter it
- runs under (the side python)."""
- python = sideenv_python()
- if python is None:
- raise RuntimeError(_local_runtime_hint("the isolated runtime is not installed"))
- profile = str(config.get("profile", "hermes") or "hermes")
- env = _daemon_subprocess_env(config)
- logger.info("Hindsight embedded: starting side-env daemon manager (profile=%s, side_python=%s)",
- profile, python)
- timeout = float(config.get("daemon_start_timeout") or _DEFAULT_DAEMON_START_TIMEOUT)
- try:
- result = subprocess.run( # noqa: S603 — fixed argv (python -c bridge), no shell
- [str(python), "-c", _DAEMON_BRIDGE_CODE, profile, "restart" if restart else "start"],
- env=env, capture_output=True, text=True, encoding="utf-8",
- errors="replace", timeout=timeout,
- )
- except subprocess.TimeoutExpired as exc:
- logger.warning("Hindsight embedded daemon start timed out after %.0fs (profile=%s)", timeout, profile)
- raise RuntimeError(
- f"Hindsight daemon start timed out after {timeout:.0f}s; the first start "
- "can take several minutes — check the hindsight profile log and retry."
- ) from exc
- except OSError as exc:
- raise RuntimeError(f"could not run the side-env runtime {python}: {exc}") from exc
- if result.returncode != 0:
- detail = (result.stderr or result.stdout or "").strip()[-2000:]
- logger.warning("Hindsight embedded daemon bridge failed (exit %s): %s", result.returncode, detail)
- raise RuntimeError(f"Hindsight daemon startup failed (exit {result.returncode}): {detail}")
- payload = _parse_bridge_output(result.stdout)
- url = payload.get("url")
- if payload.get("ok") and url:
- logger.info("Hindsight embedded: daemon ready at %s (profile=%s)", url, profile)
- return str(url)
- error = payload.get("error") or f"no bridge result in side-env output: {(result.stdout or '')[-500:]}"
- logger.warning("Hindsight embedded daemon did not start: %s", error)
- raise RuntimeError(f"Hindsight daemon startup failed: {error}")
diff --git a/plugins/memory/hindsight/plugin.yaml b/plugins/memory/hindsight/plugin.yaml
deleted file mode 100644
index 99b4000b8e8..00000000000
--- a/plugins/memory/hindsight/plugin.yaml
+++ /dev/null
@@ -1,5 +0,0 @@
-name: hindsight
-version: 1.0.0
-description: "Hindsight — long-term memory with knowledge graph, entity resolution, and multi-strategy retrieval."
-extra: hindsight
-requires_env: []
diff --git a/plugins/memory/hindsight/settings.py b/plugins/memory/hindsight/settings.py
deleted file mode 100644
index f6d42b695c8..00000000000
--- a/plugins/memory/hindsight/settings.py
+++ /dev/null
@@ -1,127 +0,0 @@
-"""Hindsight plugin constants and pure config normalizers (no I/O, no origin imports)."""
-
-from __future__ import annotations
-
-import contextlib
-import json
-import logging
-import re
-from typing import Any, List
-
-# Log under the plugin package's own logger name (loader-path independent).
-logger = logging.getLogger(__name__.rpartition(".")[0])
-
-_DEFAULT_API_URL = "https://api.hindsight.vectorize.io"
-_DEFAULT_LOCAL_URL = "http://localhost:8888"
-
-_DEFAULT_TIMEOUT = 120 # seconds — cloud API can take 30-40s per request
-_DEFAULT_IDLE_TIMEOUT = 300 # seconds — Hindsight embedded daemon default
-# ``metadata.source`` on retained memories is OPT-IN (AGENTS.md forbids
-# on-by-default attribution tags): ``retain_source`` / HINDSIGHT_RETAIN_SOURCE.
-_DEFAULT_RETAIN_SOURCE = ""
-# Hindsight brand mark (eye ringed by graph nodes) for the recall/retain indicators.
-_HINDSIGHT_GLYPH = "👁️"
-# Hindsight 0.5.0 added ``update_mode='append'``; older APIs would silently
-# overwrite prior turns under a stable document_id, so they keep the per-process id.
-# Mirrors hindsight-integrations/openclaw — Hindsight 0.5.0 added `update_mode='append'` semantics on retain
-# (vectorize-io/hindsight#932).
-_MIN_VERSION_FOR_UPDATE_MODE_APPEND = "0.5.0"
-_VALID_BUDGETS = {"low", "mid", "high"}
-_PROVIDER_DEFAULT_MODELS = {
- "openai": "gpt-4o-mini",
- "anthropic": "claude-haiku-4-5",
- "gemini": "gemini-3.6-flash",
- "groq": "openai/gpt-oss-120b",
- "openrouter": "qwen/qwen3.5-9b",
- "minimax": "MiniMax-M2.7",
- "ollama": "gemma3:12b",
- "lmstudio": "local-model",
- "openai_compatible": "your-model-name",
-}
-# The embedded daemon speaks OpenAI wire format for these providers.
-_OPENAI_WIRE_PROVIDERS = {"openai_compatible", "openrouter"}
-_OBSERVATION_SCOPE_KEYWORDS = {"per_tag", "combined", "all_combinations"}
-
-
-def _parse_int_setting(value: Any, default: int) -> int:
- """Parse an integer config/env value, falling back on invalid input."""
- if value is None or value == "":
- return default
- try:
- return int(value)
- except (TypeError, ValueError):
- logger.warning("Invalid integer Hindsight setting %r; using default %s", value, default)
- return default
-
-
-def _daemon_llm_provider(provider: str) -> str:
- return "openai" if provider in _OPENAI_WIRE_PROVIDERS else provider
-
-
-def _normalize_retain_tags(value: Any) -> List[str]:
- """Normalize tag config/tool values to a deduplicated list of strings."""
- if value is None:
- return []
- raw_items = value if isinstance(value, list) else [value]
- if isinstance(value, str):
- text = value.strip()
- parsed = None
- if text.startswith("["):
- with contextlib.suppress(Exception):
- parsed = json.loads(text)
- raw_items = parsed if isinstance(parsed, list) else text.split(",")
- normalized: list[str] = []
- for item in raw_items:
- tag = str(item).strip()
- if tag and tag not in normalized:
- normalized.append(tag)
- return normalized
-
-
-def _normalize_observation_scopes(value: Any) -> Any:
- """Normalize observation_scopes to a keyword string, ``list[list[str]]`` (one inner
- list per consolidation pass), or ``None`` (Hindsight's ``combined`` default).
- Accepts a keyword, a JSON-encoded list, a flat tag list (one scope) or a list of
- tag-lists; anything unrecognized -> ``None`` so we never send an invalid payload."""
- if isinstance(value, str):
- text = value.strip()
- if text in _OBSERVATION_SCOPE_KEYWORDS:
- return text
- if text.startswith("["):
- try:
- return _normalize_observation_scopes(json.loads(text))
- except Exception:
- return None
- return None
- if not isinstance(value, (list, tuple)):
- return None
- if all(isinstance(entry, str) for entry in value): # flat tag list -> one scope
- value = [value]
- scopes = [
- [str(tag).strip() for tag in entry if str(tag).strip()] if isinstance(entry, (list, tuple))
- else [entry.strip()] if isinstance(entry, str) and entry.strip() else []
- for entry in value
- ]
- return [s for s in scopes if s] or None
-
-
-def _sanitize_bank_segment(value: str) -> str:
- """URL/filesystem-safe bank_id placeholder: runs outside ``[A-Za-z0-9_-]`` (per
- ``str.isalnum``) become one dash; leading/trailing ``-``/``_`` are stripped."""
- # \w == str.isalnum() + "_" for str patterns, so this matches the per-char rule.
- return re.sub(r"[^\w-]+", "-", str(value)).strip("-_") if value else ""
-
-
-def _resolve_bank_id_template(template: str, fallback: str, **placeholders: str) -> str:
- """Render a bank_id template ({profile}, {workspace}, {platform}, {user}, {session}),
- sanitizing each placeholder; the ``-``/``_`` runs empty placeholders leave are
- collapsed (``hermes-{user}`` -> ``hermes``). Empty/invalid template -> *fallback*."""
- if not template:
- return fallback
- try:
- rendered = template.format(**{k: _sanitize_bank_segment(v) for k, v in placeholders.items()})
- except (KeyError, IndexError) as exc:
- logger.warning("Invalid bank_id_template %r: %s — using fallback %r",
- template, exc, fallback)
- return fallback
- return re.sub(r"([-_])\1+", r"\1", rendered).strip("-_") or fallback
diff --git a/plugins/memory/hindsight/setup.py b/plugins/memory/hindsight/setup.py
deleted file mode 100644
index f1b74aee442..00000000000
--- a/plugins/memory/hindsight/setup.py
+++ /dev/null
@@ -1,213 +0,0 @@
-"""`hermes memory setup` wizard for the Hindsight provider (``post_setup``)."""
-
-from __future__ import annotations
-
-import contextlib
-import json
-import os
-import sys
-from pathlib import Path
-
-from agent.secret_scope import get_secret
-from hermes_cli.secret_prompt import masked_secret_prompt
-
-from . import templates as _hs_templates
-from .embedded import _embedded_profile_env_path, _load_simple_env, _materialize_embedded_profile_env
-from .settings import (
- _DEFAULT_API_URL, _DEFAULT_IDLE_TIMEOUT, _DEFAULT_LOCAL_URL, _DEFAULT_TIMEOUT,
- _PROVIDER_DEFAULT_MODELS,
-)
-
-_MODE_VALUES = ["cloud", "local_embedded", "local_external"]
-_MODE_ITEMS = [
- ("Cloud", "Hindsight Cloud API (lightweight, just needs an API key)"),
- ("Local Embedded", "Run Hindsight locally (downloads ~200MB, needs LLM key)"),
- ("Local External", "Connect to an existing Hindsight instance"),
-]
-
-
-def _secret_prompt(label: str) -> str:
- """Masked prompt on a TTY; plain readline when stdin is piped."""
- sys.stdout.write(label)
- sys.stdout.flush()
- return masked_secret_prompt("") if sys.stdin.isatty() else sys.stdin.readline().strip()
-
-
-def _select(title: str, items: list, values: list, current) -> str | None:
- """Curses pick from *values*, defaulting to *current*; None when cancelled."""
- from hermes_cli.memory_setup import _CANCELLED, _curses_select, _print_cancelled_setup
-
- default = values.index(current) if current in values else 0
- idx = _curses_select(title, items, default=default, cancel_returns=_CANCELLED)
- if idx == _CANCELLED:
- _print_cancelled_setup()
- return None
- return values[idx]
-
-
-def _write_env(env_path: Path, env_writes: dict) -> None:
- """Update keys in place (BOM-tolerant read: a Notepad BOM would glue U+FEFF onto
- the first key and duplicate the line), append the rest."""
- env_path.parent.mkdir(parents=True, exist_ok=True)
- existing = env_path.read_text(encoding="utf-8-sig").splitlines() if env_path.exists() else []
- updated = set()
- new_lines = []
- for line in existing:
- key = line.split("=", 1)[0].strip() if "=" in line and not line.startswith("#") else None
- new_lines.append(f"{key}={env_writes[key]}" if key in env_writes else line)
- updated.add(key)
- new_lines.extend(f"{k}={v}" for k, v in env_writes.items() if k not in updated)
- env_path.write_text("\n".join(new_lines) + "\n", encoding="utf-8")
-
-
-def _prompt_embedded_llm(llm_provider: str, provider_config: dict, env_writes: dict, hermes_env: Path) -> None:
- """local_embedded wizard step: endpoint (openai_compatible only), model, LLM key."""
- if llm_provider == "openai_compatible":
- existing_base_url = provider_config.get("llm_base_url", "")
- prompt = " LLM endpoint URL (e.g. http://192.168.1.10:8080/v1)" + (f" [{existing_base_url}]" if existing_base_url else "")
- if val := input(prompt + ": ").strip():
- provider_config["llm_base_url"] = val
- elif llm_provider == "openrouter":
- provider_config["llm_base_url"] = "https://openrouter.ai/api/v1"
- current_model = provider_config.get("llm_model") or _PROVIDER_DEFAULT_MODELS.get(llm_provider, "gpt-4o-mini")
- val = input(f" LLM model [{current_model}]: ").strip()
- provider_config["llm_model"] = val or current_model
- llm_key = _secret_prompt(" LLM API key: ")
- env_writes["HINDSIGHT_LLM_API_KEY"] = llm_key or _load_simple_env(hermes_env).get("HINDSIGHT_LLM_API_KEY", "")
-
-
-def _sync_client_dependency() -> bool:
- """hindsight-client via the declared ``extra: hindsight`` (plugin.yaml).
-
- pm's venv sync is the ONE install authority (uv.lock owns the pin) — no
- pip against sys.executable, and no ``tools.lazy_deps`` (deleted)."""
- try:
- import pm
-
- pm.sync_venv(["hindsight"], explicit=True)
- return True
- except Exception as e:
- print(f" ⚠ Install failed: {e}")
- print(" Run manually: hermes pm install")
- return False
-
-
-def _install_embedded_runtime() -> bool:
- """local_embedded: install the isolated side env (hindsight-embed + the heavy
- hindsight-api-slim[all]) via PM's isolated environment operation — never the
- shared main venv (the protobuf floors conflict). The daemon later runs from the
- side env's own interpreter/binary; Hermes talks HTTP with hindsight-client."""
- from .embedded_runtime import _local_runtime_hint, ensure_sideenv, sideenv_root
-
- try:
- ensure_sideenv()
- except Exception as e:
- print(f" ⚠ Isolated runtime install failed: {e}")
- print(f" {_local_runtime_hint(str(e)).strip()}")
- return False
- print(f" ✓ Isolated Hindsight runtime installed at {sideenv_root()}")
- print(" (separate environment — the Hermes venv is not modified; the daemon")
- print(" runs from it and Hermes connects over HTTP)")
- return True
-
-
-def run_setup(provider, hermes_home: str, config: dict) -> None:
- """Interactive wizard — installs only the deps the selected mode needs."""
- from hermes_cli.config import save_config
-
- from . import _load_config
-
- print("\n Configuring Hindsight memory:\n")
-
- existing_config = provider._config if isinstance(provider._config, dict) else _load_config()
- if not isinstance(existing_config, dict):
- existing_config = {}
-
- mode = _select(" Select mode", _MODE_ITEMS, _MODE_VALUES, existing_config.get("mode"))
- if mode is None:
- return
- provider_config: dict = dict(existing_config, mode=mode)
- env_writes: dict = {}
- hermes_env = Path(hermes_home) / ".env"
-
- llm_provider = ""
- if mode == "local_embedded":
- llm_items = [(p, f"default model: {m}") for p, m in _PROVIDER_DEFAULT_MODELS.items()]
- llm_provider = _select(" Select LLM provider", llm_items, list(_PROVIDER_DEFAULT_MODELS),
- provider_config.get("llm_provider"))
- if llm_provider is None:
- return
- provider_config["llm_provider"] = llm_provider
-
- print("\n Checking dependencies...")
- # Environment-aware install: pm's venv sync is the ONE authority for the
- # client (declared extra, uv.lock pin); tools.lazy_deps is deleted. The
- # local_embedded heavy stack installs into its own isolated side env.
- if not _sync_client_dependency():
- return
- if mode == "local_embedded" and not _install_embedded_runtime():
- return
-
- if mode == "cloud":
- print("\n Get your API key at https://ui.hindsight.vectorize.io\n")
- existing_key = get_secret("HINDSIGHT_API_KEY", "") or ""
- masked = f"...{existing_key[-4:]}" if len(existing_key) > 4 else "set"
- api_key = _secret_prompt(f" API key (current: {masked}, blank to keep): " if existing_key else " API key: ")
- if api_key:
- env_writes["HINDSIGHT_API_KEY"] = api_key
- if val := input(f" API URL [{_DEFAULT_API_URL}]: ").strip():
- provider_config["api_url"] = val
- elif mode == "local_external":
- val = input(f" Hindsight API URL [{_DEFAULT_LOCAL_URL}]: ").strip()
- provider_config["api_url"] = val or _DEFAULT_LOCAL_URL
- if api_key := _secret_prompt(" API key (optional, blank to skip): "):
- env_writes["HINDSIGHT_API_KEY"] = api_key
- else:
- _prompt_embedded_llm(llm_provider, provider_config, env_writes, hermes_env)
-
- provider_config.setdefault("bank_id", "hermes")
- provider_config.setdefault("recall_budget", "mid")
- # Preserve explicit 0 timeouts instead of treating them as blank.
- timeouts = [("timeout", "HINDSIGHT_TIMEOUT", _DEFAULT_TIMEOUT)]
- if mode == "local_embedded":
- timeouts.append(("idle_timeout", "HINDSIGHT_IDLE_TIMEOUT", _DEFAULT_IDLE_TIMEOUT))
- for key, env_key, default in timeouts:
- value = provider_config.get(key)
- provider_config[key] = value = default if value is None else value
- env_writes[env_key] = str(value)
- config["memory"]["provider"] = "hindsight"
- save_config(config)
- provider.save_config(provider_config, hermes_home)
- if env_writes:
- _write_env(hermes_env, env_writes)
-
- # Starter template (best-effort) only where the API is reachable now
- # (local_embedded's daemon isn't up).
- if _hs_templates.supported_for_mode(mode):
- from hermes_cli.memory_setup import _CANCELLED, _curses_select
-
- default_url = _DEFAULT_LOCAL_URL if mode == "local_external" else _DEFAULT_API_URL
- _hs_templates.run_template_step(
- api_url=provider_config.get("api_url") or default_url,
- bank_id=provider_config.get("bank_id", "hermes"),
- api_key=env_writes.get("HINDSIGHT_API_KEY") or os.environ.get("HINDSIGHT_API_KEY", "") or None,
- select=_curses_select, cancelled=_CANCELLED,
- )
-
- if mode == "local_embedded":
- materialized_config = dict(provider_config)
- with contextlib.suppress(Exception):
- materialized_config = json.loads(
- (Path(hermes_home) / "hindsight" / "config.json").read_text(encoding="utf-8-sig")
- )
- llm_api_key = (
- env_writes.get("HINDSIGHT_LLM_API_KEY", "")
- or _load_simple_env(hermes_env).get("HINDSIGHT_LLM_API_KEY", "")
- or _load_simple_env(_embedded_profile_env_path(materialized_config)).get("HINDSIGHT_API_LLM_API_KEY", "")
- )
- _materialize_embedded_profile_env(materialized_config, llm_api_key=llm_api_key or None)
-
- print(f"\n ✓ Hindsight memory configured ({mode} mode)")
- if env_writes:
- print(" API keys saved to .env")
- print("\n Start a new session to activate.\n")
diff --git a/plugins/memory/hindsight/templates.py b/plugins/memory/hindsight/templates.py
deleted file mode 100644
index bf71258714b..00000000000
--- a/plugins/memory/hindsight/templates.py
+++ /dev/null
@@ -1,128 +0,0 @@
-"""Starter bank templates for the Hindsight setup wizard: fetch the Bank Templates
-catalog, filter to the ``hermes`` integration, apply a manifest via
-``POST /v1/default/banks/{bank}/import`` (creates the bank if missing).
-Catalog source overridable with ``HINDSIGHT_TEMPLATES_URL`` (pin/mirror).
-"""
-
-from __future__ import annotations
-
-import json
-import logging
-import os
-import urllib.request
-from urllib.parse import urljoin
-
-from hermes_cli.urllib_security import open_credentialed_url
-
-logger = logging.getLogger(__name__)
-
-# Same file that powers hindsight.vectorize.io/templates.
-_DEFAULT_CATALOG_URL = (
- "https://raw.githubusercontent.com/vectorize-io/hindsight/main/"
- "hindsight-docs/src/data/templates.json"
-)
-_HTTP_TIMEOUT = 15
-
-# The API must be reachable during setup; a local_embedded daemon isn't up yet.
-SUPPORTED_MODES = ("cloud", "local_external")
-
-
-def supported_for_mode(mode: str) -> bool:
- return mode in SUPPORTED_MODES
-
-
-def catalog_url() -> str:
- return os.environ.get("HINDSIGHT_TEMPLATES_URL", _DEFAULT_CATALOG_URL)
-
-
-def _get_json(url: str) -> dict:
- req = urllib.request.Request(url, headers={"Accept": "application/json"})
- with urllib.request.urlopen(req, timeout=_HTTP_TIMEOUT) as resp: # noqa: S310 - fixed https catalog
- return json.loads(resp.read().decode("utf-8"))
-
-
-def fetch_hermes_templates(url: str | None = None) -> list[dict]:
- """Return catalog entries tagged for the ``hermes`` integration."""
- catalog = _get_json(url or catalog_url())
- entries = catalog.get("templates", []) if isinstance(catalog, dict) else []
- return [e for e in entries if "hermes" in (e.get("integrations") or [])]
-
-
-def fetch_manifest(entry: dict, url: str | None = None) -> dict:
- """Fetch the BankTemplateManifest JSON for a catalog entry (``manifest_file`` is
- relative to the catalog, e.g. "templates/foo.json")."""
- return _get_json(urljoin(url or catalog_url(), entry["manifest_file"]))
-
-
-def _bank_request(api_url: str, bank_id: str, api_key: str | None, action: str, *, headers: dict, **kwargs):
- if api_key:
- headers = {**headers, "Authorization": f"Bearer {api_key}"}
- endpoint = f"{api_url.rstrip('/')}/v1/default/banks/{bank_id}/{action}"
- return urllib.request.Request(endpoint, headers=headers, **kwargs) # noqa: S310
-
-
-def apply_template(api_url: str, bank_id: str, api_key: str | None, manifest: dict) -> None:
- """Apply a manifest to a bank via the import endpoint. Raises on failure."""
- req = _bank_request(api_url, bank_id, api_key, "import", data=json.dumps(manifest).encode("utf-8"),
- headers={"Content-Type": "application/json"}, method="POST")
- with open_credentialed_url(req, timeout=_HTTP_TIMEOUT) as resp:
- resp.read() # drain; open_credentialed_url raises HTTPError on non-2xx
-
-
-def probe_existing_customization(api_url: str, bank_id: str, api_key: str | None) -> bool:
- """Best-effort: True if the bank already has template-level config, mental models
- or directives (a template would overwrite them). A missing bank or any error
- counts as "not customized": the step must never block on this probe."""
- req = _bank_request(api_url, bank_id, api_key, "export", headers={"Accept": "application/json"})
- try:
- with open_credentialed_url(req, timeout=_HTTP_TIMEOUT) as resp:
- data = json.loads(resp.read().decode("utf-8"))
- except Exception as e: # missing bank / network — treat as not customized
- logger.debug("Hindsight: bank customization probe skipped: %s", e)
- return False
- return bool(data.get("bank") or data.get("mental_models") or data.get("directives"))
-
-
-def run_template_step(*, api_url: str, bank_id: str, api_key: str | None, select, cancelled, log=print) -> str | None:
- """Wizard starter-template step. ``select(title, items, default, cancel_returns)``
- is the picker (injected: testable without curses). Returns the applied template
- id, or None if skipped/blank/failed. Never raises — a template is a nice-to-have."""
- try:
- entries = fetch_hermes_templates()
- except Exception as e: # network/parse — non-fatal
- logger.debug("Hindsight: could not fetch templates: %s", e)
- return None
- if not entries:
- return None
-
- items = [(e.get("name", e["id"]), (e.get("description") or "")[:72]) for e in entries]
- items.append(("Blank", "Start with an empty memory bank"))
- idx = select(" Starter memory template", items, default=0, cancel_returns=cancelled)
- if idx == cancelled or idx >= len(entries):
- return None # blank or cancelled
-
- entry = entries[idx]
-
- # Re-running setup on a configured bank: a template overwrites its config and
- # upserts models/directives — confirm before clobbering.
- if probe_existing_customization(api_url, bank_id, api_key):
- confirm = select(
- f" Bank '{bank_id}' already has memory settings — apply this template on top?",
- [("Apply", "Overwrite config; add/update mental models & directives"),
- ("Keep existing", "Leave the bank as-is")],
- default=1,
- cancel_returns=cancelled,
- )
- if confirm != 0:
- log(f" Kept existing settings for bank '{bank_id}'.")
- return None
-
- try:
- manifest = fetch_manifest(entry)
- apply_template(api_url, bank_id, api_key, manifest)
- log(f" ✓ Applied '{entry.get('name', entry['id'])}' template to bank '{bank_id}'")
- return entry["id"]
- except Exception as e:
- log(f" ⚠ Could not apply template ({e}). You can apply one later from "
- f"hindsight.vectorize.io/templates.")
- return None
diff --git a/scripts/install.ps1 b/scripts/install.ps1
index ab575d44a33..488d417eb9e 100644
--- a/scripts/install.ps1
+++ b/scripts/install.ps1
@@ -6,6 +6,7 @@
# -NonInteractive skip stages that need input
# -IncludeDesktop add the desktop build stage
# -ProtocolVersion print the stage protocol version
+[CmdletBinding(PositionalBinding=$false)]
param(
[string]$Branch = "main",
[string]$Commit = "",
@@ -410,7 +411,11 @@ function Get-Uv {
}
$entry = Join-Path (Get-PmStoreRoot) "uv-$($script:UvPinVersion)-$target"
$uvExe = Join-Path $entry "uv.exe"
- if (Test-Path $uvExe) { return $uvExe }
+ if (Test-Path $uvExe) {
+ if (Test-UvAtLeastPin $uvExe) { return $uvExe }
+ Log "cached pinned uv does not run; restaging it"
+ Remove-Item -Path $uvExe -Force
+ }
Log "staging pinned uv $($script:UvPinVersion) ($target) into the pm store"
$tmpDir = Join-Path ([IO.Path]::GetTempPath()) "hermes-uv-bootstrap-$PID"
try {
@@ -690,9 +695,12 @@ function Get-BootstrapPython {
$lock = Get-Content (Join-Path $InstallDir "pm\lock.json") -Raw | ConvertFrom-Json
$pyPin = $lock.packages.python
$pyVersion = if ($pyPin) { ($pyPin.version -split '\+')[0] -replace '^(\d+\.\d+).*', '$1' } else { '3.14' }
- Invoke-Native { & $uv python install --no-bin --no-registry $pyVersion } | Out-Host
- if ($LASTEXITCODE) { Fail "bootstrap Python installation failed" }
- $bootPy = (Invoke-Native { & $uv python find --managed-python --no-project $pyVersion }) -join "`n"
+ $bootPy = (Invoke-Native { & $uv python find --managed-python --no-project $pyVersion 2>$null }) -join "`n"
+ if ($LASTEXITCODE -or -not $bootPy) {
+ Invoke-Native { & $uv python install --no-bin --no-registry $pyVersion } | Out-Host
+ if ($LASTEXITCODE) { Fail "bootstrap Python installation failed" }
+ $bootPy = (Invoke-Native { & $uv python find --managed-python --no-project $pyVersion }) -join "`n"
+ }
if ($LASTEXITCODE -or -not $bootPy) { Fail "bootstrap Python lookup failed" }
return $bootPy.Trim()
}
diff --git a/scripts/install.sh b/scripts/install.sh
index ce7108edbc6..24992f824de 100755
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@ -31,7 +31,7 @@ INCLUDE_DESKTOP=false
while [ $# -gt 0 ]; do
case "$1" in
- --branch|-Branch) BRANCH="$2"; shift 2 ;;
+ --branch|-Branch) BRANCH="${2:?--branch needs a value}"; shift 2 ;;
--commit|-Commit) INSTALL_COMMIT="$2"; shift 2 ;;
--dir) INSTALL_DIR="$2"; shift 2 ;;
--hermes-home|-HermesHome) HERMES_HOME="$2"; shift 2 ;;
@@ -39,7 +39,10 @@ while [ $# -gt 0 ]; do
--stage|-Stage) STAGE="$2"; shift 2 ;;
--json|-Json) JSON=true; shift ;;
--non-interactive|-NonInteractive) NON_INTERACTIVE=true; shift ;;
- --skip-setup|--skip-browser) NON_INTERACTIVE=true; shift ;;
+ --skip-setup) NON_INTERACTIVE=true; shift ;;
+ --skip-browser|--no-playwright)
+ echo "$1 no longer skips the browser install; pm manages browser dependencies. Remove this flag and use --non-interactive to skip setup prompts." >&2
+ exit 1 ;;
--include-desktop|-IncludeDesktop) INCLUDE_DESKTOP=true; shift ;;
-h|--help)
echo "Usage: install.sh [--branch NAME] [--commit SHA] [--dir PATH]"
diff --git a/scripts/update-test/hermes-update-rehearsal.sh b/scripts/update-test/hermes-update-rehearsal.sh
index 955e2569034..a0f46543828 100755
--- a/scripts/update-test/hermes-update-rehearsal.sh
+++ b/scripts/update-test/hermes-update-rehearsal.sh
@@ -470,10 +470,12 @@ cmd_post() {
say " to how they were at $SNAP"
confirm "Put everything back from $SNAP?"
- step "stopping Hermes"
- pkill -f "Hermes.app/Contents/MacOS" 2>/dev/null || true
- pkill -f "hermes gateway" 2>/dev/null || true
- ok "asked Hermes to stop (if anything was running)"
+ step "stopping this home's gateway"
+ local hermes_exe
+ hermes_exe="$(resolve_hermes_exe)" || die "no Hermes launcher for $INSTALL_DIR; stop this home's gateway before restoring"
+ HERMES_HOME="$HERMES_HOME" "$hermes_exe" gateway stop \
+ || die "could not stop this home's gateway; restore has not started"
+ ok "stopped this home's gateway (close the desktop app before restoring its data)"
local aside="$SNAP/replaced"
[ ! -e "$aside" ] || die "$aside already exists (an interrupted post?) — nothing was changed; move it away and run post again"
diff --git a/tests/agent/test_memory_session_switch.py b/tests/agent/test_memory_session_switch.py
index 013eac2aec7..d65a2588740 100644
--- a/tests/agent/test_memory_session_switch.py
+++ b/tests/agent/test_memory_session_switch.py
@@ -9,8 +9,6 @@ for scoped writes) keep writing into the old session's record.
-import pytest
-
from agent.memory_manager import MemoryManager
from agent.memory_provider import MemoryProvider
@@ -112,111 +110,3 @@ def test_manager_isolates_provider_failures():
# ---------------------------------------------------------------------------
# MemoryManager.sync_all / queue_prefetch_all — session_id propagation
# ---------------------------------------------------------------------------
-
-
-
-
-
-
-# ---------------------------------------------------------------------------
-# Hindsight reference implementation — state-flush semantics
-# ---------------------------------------------------------------------------
-
-
-def _make_hindsight_provider():
- """Build a bare HindsightMemoryProvider that skips network setup.
-
- We instantiate without importing optional deps at class-level by
- bypassing __init__ and seeding the attributes on_session_switch
- reads/writes. This keeps the test hermetic.
- """
- import threading
- hindsight_mod = pytest.importorskip("plugins.memory.hindsight")
- provider = object.__new__(hindsight_mod.HindsightMemoryProvider)
- provider._session_id = "old-sid"
- provider._parent_session_id = ""
- provider._document_id = "old-sid-20260101_000000_000000"
- provider._session_turns = ["turn-1", "turn-2"]
- provider._turn_counter = 2
- provider._turn_index = 2
- # Attrs read by _build_metadata / _build_retain_kwargs when the
- # buffer-flush path on session switch fires. Empty strings keep the
- # metadata minimal but well-formed.
- provider._retain_source = ""
- provider._platform = ""
- provider._user_id = ""
- provider._user_name = ""
- provider._chat_id = ""
- provider._chat_name = ""
- provider._chat_type = ""
- provider._thread_id = ""
- provider._agent_identity = ""
- provider._agent_workspace = ""
- provider._retain_tags = []
- provider._retain_context = "test-context"
- provider._retain_async = False
- provider._bank_id = "test-bank"
- # Prefetch state the switch path drains/clears.
- provider._prefetch_thread = None
- provider._prefetch_lock = threading.Lock()
- provider._prefetch_result = ""
- # Sync thread tracking (legacy alias at the writer).
- provider._sync_thread = None
- # Writer queue infra the flush-on-switch path enqueues onto. We stub
- # _ensure_writer / _register_atexit so no real thread is spawned;
- # tests exercising flush delivery live in
- # tests/plugins/memory/test_hindsight_provider.py where the full
- # writer-queue wiring is in place.
- import queue as _queue
- provider._retain_queue = _queue.Queue()
- provider._shutting_down = threading.Event()
- provider._atexit_registered = True
- provider._ensure_writer = lambda: None
- provider._register_atexit = lambda: None
- # Mode + API state used by _resolve_retain_target; stub the resolver
- # so tests don't actually probe the API. Real probe behavior is
- # exercised by tests in tests/plugins/memory/test_hindsight_provider.py.
- provider._mode = "cloud"
- provider._api_url = ""
- provider._api_key = ""
- provider._client = None
- provider._resolve_retain_target = lambda fb: (fb, None)
- # Stub the network-touching helper so any enqueued flush closure is
- # a no-op if ever drained in a unit test.
- provider._run_hindsight_operation = lambda _op: None
- return provider
-
-
-def test_hindsight_on_session_switch_updates_session_id_and_mints_fresh_doc():
- provider = _make_hindsight_provider()
- old_doc = provider._document_id
-
- provider.on_session_switch(
- "new-sid", parent_session_id="old-sid", reset=False, reason="resume"
- )
-
- assert provider._session_id == "new-sid"
- assert provider._parent_session_id == "old-sid"
- # Document id MUST be fresh — else next retain overwrites old session doc
- assert provider._document_id != old_doc
- assert provider._document_id.startswith("new-sid-")
-
-
-def test_hindsight_on_session_switch_clears_turn_buffers():
- """Accumulated _session_turns must not leak into the next session.
-
- Hindsight batches turns under a single _document_id. If the buffer
- isn't cleared on switch, the next retain under the new _document_id
- flushes turns that belong to the previous session.
- """
- provider = _make_hindsight_provider()
- provider.on_session_switch("new-sid", parent_session_id="old-sid")
- assert provider._session_turns == []
- assert provider._turn_counter == 0
- assert provider._turn_index == 0
-
-
-
-
-
-
diff --git a/tests/conftest.py b/tests/conftest.py
index 3c72e843fbd..4203a92fecd 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -105,9 +105,10 @@ def _hermes_home_points_at_production(value: str) -> bool:
# root ends up INSIDE a guarded real home (the operator's, or a custom one
# honored below), so the session sandbox, pytest's basetemp and every
# ``tempfile`` default in the code under test trip the real-home guard. Strip
-# Hermes' own export (the marker tells it apart from a user-set var, which is
-# left alone) and pin the system default so the import-time hook stays a
-# no-op. The parallel runner exports its own disk-backed TMPDIR anyway.
+# Hermes' own export (the marker tells it apart from a user-set var), and
+# relocate even user-set temp directories inside a guarded home. Pin the
+# system default so the import-time hook stays a no-op. The parallel runner
+# exports its own disk-backed TMPDIR anyway.
from hermes_constants import SCRATCH_DIR_MARKER_ENV, SCRATCH_TMP_ENV_VARS
_HERMES_EXPORTED_TMP = os.environ.get(SCRATCH_DIR_MARKER_ENV, "")
@@ -116,7 +117,21 @@ if _HERMES_EXPORTED_TMP:
if os.environ.get(_key, "").strip() == _HERMES_EXPORTED_TMP:
del os.environ[_key]
del os.environ[SCRATCH_DIR_MARKER_ENV]
- tempfile.tempdir = None # drop the cached redirect so gettempdir() re-resolves
+
+from hermes_state_guard import _real_platform_state_root
+
+_real_test_root = _real_platform_state_root() or (Path.home() / ".hermes").resolve()
+_guarded_tmp_roots = [_real_test_root]
+_custom_test_home = os.environ.get("HERMES_HOME")
+if _custom_test_home:
+ _guarded_tmp_roots.append(Path(_custom_test_home).expanduser().resolve())
+for _key in SCRATCH_TMP_ENV_VARS:
+ _value = os.environ.get(_key)
+ if _value:
+ _path = Path(_value).expanduser().resolve()
+ if any(_path.is_relative_to(_root) for _root in _guarded_tmp_roots):
+ del os.environ[_key]
+tempfile.tempdir = None # re-resolve after stripping guarded temp directories
os.environ.setdefault("TMPDIR", tempfile.gettempdir())
if _hermes_home_points_at_production(os.environ.get("HERMES_HOME", "")):
diff --git a/tests/git_safety.py b/tests/git_safety.py
index 3e8b8102fc1..58c99514279 100644
--- a/tests/git_safety.py
+++ b/tests/git_safety.py
@@ -9,6 +9,7 @@ _WRAPPERS = {"env", "nohup", "setsid", "timeout", "sudo", "xargs", "nice", "ioni
_MUTATIONS = {
"pull", "reset", "stash", "checkout", "switch", "restore",
"clean", "rebase", "merge", "cherry-pick", "revert", "apply", "am",
+ "commit", "add", "rm", "update-ref", "branch", "worktree", "tag",
}
_TARGET_OPTIONS = {"--git-dir", "--work-tree"}
_VALUE_OPTIONS = _TARGET_OPTIONS | {"-C", "-c", "--namespace", "--super-prefix"}
@@ -84,10 +85,22 @@ def blocked_git_mutation(cmd, kwargs, protected_roots):
if tail is None:
return None
verb, targets, after = _git_verb_and_targets(tail, kwargs or {})
- if verb not in _MUTATIONS:
+ if verb == "config":
+ # Querying config is safe; writing URL rewrites into the checkout is not.
+ if any(arg in {"--get", "--get-all", "--get-regexp", "--list", "-l"} for arg in after):
+ return None
+ if not any("url." in arg and ".insteadof" in arg.lower() for arg in after):
+ return None
+ elif verb not in _MUTATIONS:
return None
if verb == "stash" and after and after[0] in {"list", "show"}:
return None
+ if verb == "worktree" and after and after[0] == "list":
+ return None
+ if verb == "branch" and (not after or after[0] in {"--list", "--show-current", "-a", "-r", "-v", "-vv"}):
+ return None
+ if verb == "tag" and (not after or after[0] in {"--list", "-l"}):
+ return None
for target in targets:
try:
resolved = target.resolve()
diff --git a/tests/hermes_cli/test_banner.py b/tests/hermes_cli/test_banner.py
index 9e22ecb1720..41d2d325aca 100644
--- a/tests/hermes_cli/test_banner.py
+++ b/tests/hermes_cli/test_banner.py
@@ -83,3 +83,10 @@ def test_build_welcome_banner_does_not_center_pad_hero_art():
hero_line = next(line for line in buf.getvalue().splitlines() if "\u2800X" in line)
assert hero_line.startswith("\u2502 \u2800X"), repr(hero_line)
+
+
+def test_baked_banner_uses_live_identity(monkeypatch):
+ from hermes_cli import banner, version_info
+
+ monkeypatch.setattr(version_info, "get_code_identity", lambda: {"short_sha": "a1b2c3d4"})
+ assert banner._baked_banner_state() == {"upstream": "a1b2c3d4", "local": "a1b2c3d4", "ahead": 0}
diff --git a/tests/hermes_cli/test_plugins_check_updates.py b/tests/hermes_cli/test_plugins_check_updates.py
index 8d967d52460..2090ffde8b4 100644
--- a/tests/hermes_cli/test_plugins_check_updates.py
+++ b/tests/hermes_cli/test_plugins_check_updates.py
@@ -482,3 +482,25 @@ def test_default_fetch_refuses_non_https_feeds_before_any_request(monkeypatch, u
monkeypatch.setattr(urllib.request, "urlopen", never)
with pytest.raises(ValueError, match="https://"):
default_fetch(url)
+
+
+def test_default_fetch_refuses_https_to_http_redirect_before_reading(monkeypatch):
+ import urllib.request
+ from hermes_cli.plugins_updates import default_fetch
+
+ class RedirectedResponse:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ pass
+
+ def geturl(self):
+ return "http://feed.example/insecure.yml"
+
+ def read(self, *_):
+ raise AssertionError("insecure feed must not be read")
+
+ monkeypatch.setattr(urllib.request, "urlopen", lambda *_a, **_kw: RedirectedResponse())
+ with pytest.raises(ValueError, match="https://"):
+ default_fetch("https://feed.example/secure.yml")
diff --git a/tests/install/windows-e2e.ps1 b/tests/install/windows-e2e.ps1
index a63b502c177..2deb554f544 100644
--- a/tests/install/windows-e2e.ps1
+++ b/tests/install/windows-e2e.ps1
@@ -446,9 +446,10 @@ function Invoke-RefInstaller {
$script = Join-Path $WorkRoot "install-$Label.ps1"
(Invoke-Git @("-C", $RepoRoot, "show", "$Ref`:scripts/install.ps1")) -join "`n" |
Set-Content -LiteralPath $script -Encoding UTF8
- $flags = @("-SkipSetup", "-HermesHome", $HermesHome, "-InstallDir", $InstallDir)
+ $flags = @("-HermesHome", $HermesHome, "-InstallDir", $InstallDir)
$text = Get-Content -LiteralPath $script -Raw
if ($text -match '\$NonInteractive') { $flags += "-NonInteractive" }
+ else { $flags += "-SkipSetup" }
if ($IncludeDesktop) {
# The desktop stage is the point of this leg: a ref without the
# parameter is a hard failure, not a silent plain install.
diff --git a/tests/plugins/memory/test_bom_tolerant_config_reads.py b/tests/plugins/memory/test_bom_tolerant_config_reads.py
index 5462eb3c9bd..6f0868a255f 100644
--- a/tests/plugins/memory/test_bom_tolerant_config_reads.py
+++ b/tests/plugins/memory/test_bom_tolerant_config_reads.py
@@ -2,7 +2,7 @@
Notepad and PowerShell ``>`` prepend U+FEFF when saving; ``json.loads`` rejects it
("Unexpected UTF-8 BOM") and every loader below degrades to defaults, so a user who
-edited mem0.json / honcho.json / hindsight config.json / supermemory.json lost the
+edited mem0.json / honcho.json / supermemory.json lost the
whole config with no error (Qwen CLI creds raised ``qwen_auth_read_failed``). Same
class as the auth-store/.env sweep; these were the missed sibling readers.
"""
@@ -20,7 +20,7 @@ def _write_bom_json(path: Path, payload: dict) -> Path:
def _via_shared_reader(p: Path, monkeypatch) -> dict:
- from utils import read_json_or_empty # mem0 / hindsight / honcho CLI all read through this
+ from utils import read_json_or_empty # mem0 / honcho CLI all read through this
return read_json_or_empty(p)
@@ -29,12 +29,6 @@ def _via_supermemory(p: Path, monkeypatch) -> dict:
return _load_supermemory_config(str(p.parent))
-def _via_hindsight_config(p: Path, monkeypatch) -> dict:
- import plugins.memory.hindsight as hs
- monkeypatch.setattr(hs, "get_hermes_home", lambda: p.parent.parent) # <home>/hindsight/config.json
- return hs._load_config()
-
-
def _via_honcho_client(p: Path, monkeypatch) -> dict:
from plugins.memory.honcho.client import HonchoClientConfig
cfg = HonchoClientConfig.from_global_config(config_path=p)
@@ -45,7 +39,6 @@ def _via_honcho_client(p: Path, monkeypatch) -> dict:
("mem0.json", _via_shared_reader),
("supermemory.json", _via_supermemory),
("honcho.json", _via_honcho_client),
- ("hindsight/config.json", _via_hindsight_config),
])
def test_plugin_config_json_tolerates_bom(tmp_path, monkeypatch, filename, loader):
target = tmp_path / filename
diff --git a/tests/plugins/memory/test_hindsight_config_schema.py b/tests/plugins/memory/test_hindsight_config_schema.py
deleted file mode 100644
index a521ee5d2d3..00000000000
--- a/tests/plugins/memory/test_hindsight_config_schema.py
+++ /dev/null
@@ -1,51 +0,0 @@
-"""Tests for Hindsight's declared config surface."""
-
-from plugins.memory.config_schema import (
- KIND_SECRET,
- KIND_SELECT,
- get_provider_config_schema,
-)
-
-
-def test_hindsight_is_declared():
- provider = get_provider_config_schema("hindsight")
-
- assert provider is not None
- assert provider.label == "Hindsight"
- assert {field.key for field in provider.fields} == {
- "mode",
- "api_key",
- "api_url",
- "bank_id",
- "recall_budget",
- }
-
-
-def test_fields_are_all_inline():
- provider = get_provider_config_schema("hindsight")
- assert provider is not None
-
- # Hindsight is simple enough to render fully in the compact panel, so it
- # never grows a Full config… modal.
- assert all(field.inline for field in provider.fields)
-
-
-def test_mode_gating_is_expressed_as_select_options():
- provider = get_provider_config_schema("hindsight")
- assert provider is not None
-
- mode = next(field for field in provider.fields if field.key == "mode")
- assert mode.kind == KIND_SELECT
- assert mode.allowed_values() == {"cloud", "local_external"}
- # local_embedded is intentionally unsupported on desktop.
- assert "local_embedded" not in mode.allowed_values()
-
-
-def test_api_key_is_a_secret_bound_to_env():
- provider = get_provider_config_schema("hindsight")
- assert provider is not None
-
- api_key = next(field for field in provider.fields if field.key == "api_key")
- assert api_key.kind == KIND_SECRET
- assert api_key.is_secret is True
- assert api_key.env_key == "HINDSIGHT_API_KEY"
diff --git a/tests/plugins/memory/test_hindsight_embedded_runtime.py b/tests/plugins/memory/test_hindsight_embedded_runtime.py
deleted file mode 100644
index 030824c6380..00000000000
--- a/tests/plugins/memory/test_hindsight_embedded_runtime.py
+++ /dev/null
@@ -1,223 +0,0 @@
-"""Hindsight's shipped probe and bridge execute in an isolated side interpreter.
-
-The tiny SDK models only the child protocol, not upstream ML/CPU compatibility.
-PM generation acquisition is owned by tests/pm; no upstream downloads occur here.
-"""
-import json
-import os
-import subprocess
-import sys
-from pathlib import Path
-from types import SimpleNamespace
-
-import pytest
-
-import plugins.memory.hindsight.embedded_runtime as rt
-
-
-def side_root(tmp_path, monkeypatch):
- root = tmp_path / "hermes-home" / "profiles" / "Hindsight" / "env"
- monkeypatch.setattr(rt, "sideenv_root", lambda: root)
- monkeypatch.setattr(rt, "_probe_verdicts", {})
- return root
-
-
-def test_ensure_sideenv_uses_pm_selected_python(side_root, monkeypatch):
- import pm
- from pm.environments import venv_python
-
- python = venv_python(side_root / "selected")
- seen = {}
-
- def ensure(name, requirements, **kwargs):
- seen.update(name=name, requirements=requirements, **kwargs)
- return python
-
- monkeypatch.setattr(pm, "ensure_environment", ensure)
- assert rt.ensure_sideenv() == python
- assert seen == dict(
- name="hindsight", requirements=(f"hindsight-embed=={rt._EMBED_VERSION}",
- f"hindsight-api-slim[all]=={rt._API_SLIM_VERSION}"),
- root=side_root, explicit=True, timeout=3600,
- )
-
-
-def test_sideenv_python_is_pm_passive_selection(side_root, monkeypatch):
- import pm
- from pm.environments import venv_python
-
- python = venv_python(side_root / "selected")
- seen = []
- monkeypatch.setattr(pm, "environment_python",
- lambda name, **kw: seen.append((name, kw)) or python)
- assert rt.sideenv_python() == python
- assert seen == [("hindsight", {"root": side_root})]
- assert not side_root.exists()
-
-
-def side_python(side_root, monkeypatch, tmp_path):
- import pm
-
- subprocess.run([sys.executable, "-m", "venv", "--without-pip", str(side_root)],
- check=True, capture_output=True, timeout=30)
- from pm.environments import venv_python
- python = venv_python(side_root)
- site = Path(subprocess.check_output(
- [str(python), "-c", "import sysconfig; print(sysconfig.get_path('purelib'))"],
- text=True, timeout=10,
- ).strip())
- sdk = site / "hindsight_embed"
- sdk.mkdir()
- (sdk / "__init__.py").touch()
- for module in (sdk / "daemon_embed_manager.py", site / "hindsight_api.py", site / "sentence_transformers.py"):
- module.write_text("", encoding="utf-8")
- (sdk / "daemon_client.py").write_text("""import json, os, sys
-from pathlib import Path
-stopped = None
-def stop_daemon(profile):
- global stopped
- stopped = profile
-def ensure_daemon_running(config, profile):
- Path(os.environ['TEST_RECEIPT']).write_text(json.dumps({
- 'config': config, 'profile': profile, 'stopped': stopped,
- 'prefix': sys.prefix, 'env': dict(os.environ)}), encoding='utf-8')
- print('manager startup noise')
- return True
-def get_daemon_url(profile):
- return 'http://127.0.0.1:54321/' + profile
-""", encoding="utf-8")
- receipt = tmp_path / "bridge.json"
- monkeypatch.setenv("TEST_RECEIPT", str(receipt))
- monkeypatch.setattr(pm, "environment_python", lambda *a, **kw: python)
- return site, receipt
-
-
[email protected]("grace,override,expected", [
- (60, None, "60.0"), ("45", None, "45.0"), (0, None, "0.0"),
- (None, None, None), ("", None, None), ("invalid", None, None),
- (-5, None, None), (60, "99", "99"),
-])
-def test_side_interpreter_probe_and_bridge(side_python, side_root, monkeypatch, caplog, grace, override, expected):
- site, receipt = side_python
- markers = ("VIRTUAL_ENV", "PYTHONPATH", "PYTHONHOME", "PYTHONSTARTUP", "PYTHONEXECUTABLE")
- for key in markers:
- monkeypatch.setenv(key, "/invalid/main-environment")
- monkeypatch.delenv("HINDSIGHT_EMBED_PORT_HEALTH_GRACE_TIMEOUT", raising=False)
- if override:
- monkeypatch.setenv("HINDSIGHT_EMBED_PORT_HEALTH_GRACE_TIMEOUT", override)
- parent = dict(os.environ)
- assert rt.check_local_runtime() == (True, None)
- with caplog.at_level("INFO", logger=rt.__name__):
- assert rt.ensure_daemon_and_url({"profile": "test-profile", "port_health_grace_timeout": grace}, restart=True) == "http://127.0.0.1:54321/test-profile"
- child = json.loads(receipt.read_text(encoding="utf-8"))
- assert child["config"] == {}
- assert child["profile"] == child["stopped"] == "test-profile"
- assert Path(child["prefix"]) == side_root
- assert child["env"].get("HINDSIGHT_EMBED_PORT_HEALTH_GRACE_TIMEOUT") == expected
- assert child["env"]["HINDSIGHT_EMBED_API_VERSION"] == rt._API_SLIM_VERSION
- assert not set(markers).intersection(child["env"])
- assert dict(os.environ) == parent
- assert not {"hindsight_embed", "hindsight_api", "sentence_transformers"}.intersection(sys.modules)
- assert "daemon ready" in caplog.text and "starting side-env daemon manager" in caplog.text
- (site / "sentence_transformers.py").write_text("raise RuntimeError('NumPy SIMD unavailable')", encoding="utf-8")
- rt._probe_verdicts.clear() # same interpreter path mutated in place; a real reinstall is a new generation
- ok, reason = rt.check_local_runtime()
- assert not ok and "NumPy SIMD unavailable" in reason
-
-
-def test_probe_verdict_is_reused_within_the_process_until_the_interpreter_changes(side_root, monkeypatch):
- """is_available()/unavailable_reason()/initialize() each ask per session; the probe is a
- torch cold start. One spawn per interpreter path, re-probed when PM publishes a new one."""
- from pm.environments import venv_python
-
- interpreters = [venv_python(side_root / "gen-1"), venv_python(side_root / "gen-2")]
- monkeypatch.setattr(rt, "sideenv_python", lambda root=None: interpreters[0])
- spawned = []
-
- def run(argv, *a, **k):
- spawned.append(argv[0])
- return SimpleNamespace(returncode=0, stdout="", stderr="")
-
- monkeypatch.setattr(rt, "subprocess", SimpleNamespace(run=run, TimeoutExpired=subprocess.TimeoutExpired))
- for _ in range(3):
- assert rt.check_local_runtime() == (True, None)
- assert spawned == [str(interpreters[0])]
- interpreters.reverse()
- assert rt.check_local_runtime() == (True, None)
- assert spawned == [str(interpreters[1]), str(interpreters[0])]
-
-
-def test_daemon_env_is_the_served_profiles_not_the_launch_environ(tmp_path, monkeypatch):
- """Under multiplex os.environ is the LAUNCH profile's. A daemon started for a routed profile
- must see that profile's HERMES_HOME and none of the launch profile's credentials."""
- from hermes_constants import reset_hermes_home_override, set_hermes_home_override
-
- launch = tmp_path / "launch"
- routed = launch / "profiles" / "beta"
- routed.mkdir(parents=True)
- (launch / ".env").write_text("OPENAI_API_KEY=sk-launch\nHINDSIGHT_API_KEY=hs-launch\n", encoding="utf-8")
- monkeypatch.setenv("HERMES_HOME", str(launch))
- monkeypatch.setenv("OPENAI_API_KEY", "sk-launch")
- monkeypatch.setenv("HINDSIGHT_API_KEY", "hs-launch")
- monkeypatch.setenv("VIRTUAL_ENV", "/invalid/main-environment")
-
- token = set_hermes_home_override(routed)
- try:
- env = rt._daemon_subprocess_env({"port_health_grace_timeout": 30})
- finally:
- reset_hermes_home_override(token)
-
- assert Path(env["HERMES_HOME"]) == routed
- assert "OPENAI_API_KEY" not in env and "HINDSIGHT_API_KEY" not in env
- assert "VIRTUAL_ENV" not in env
- assert env["HINDSIGHT_EMBED_PORT_HEALTH_GRACE_TIMEOUT"] == "30.0"
- assert env["HINDSIGHT_EMBED_API_VERSION"] == rt._API_SLIM_VERSION
-
-
[email protected]("outcome,message", [
- (SimpleNamespace(returncode=1, stdout="", stderr="illegal instruction"), "illegal instruction"),
- (SimpleNamespace(returncode=0, stdout='__HERMES_HINDSIGHT_BRIDGE__{"ok": false, "error": "daemon refused"}', stderr=""), "daemon refused"),
- (SimpleNamespace(returncode=0, stdout="noise only", stderr=""), "no bridge result"),
- (subprocess.TimeoutExpired("side-python", 5), "timed out"),
- (OSError("cannot execute"), "could not run"),
-])
-def test_bridge_failure_is_actionable(side_root, monkeypatch, caplog, outcome, message):
- monkeypatch.setattr(rt, "sideenv_python", lambda: side_root / "python")
- def run(*args, **kwargs):
- if isinstance(outcome, Exception):
- raise outcome
- return outcome
- monkeypatch.setattr(rt, "subprocess", SimpleNamespace(run=run, TimeoutExpired=subprocess.TimeoutExpired))
- with pytest.raises(RuntimeError, match=message):
- rt.ensure_daemon_and_url({})
- if not isinstance(outcome, OSError):
- assert caplog.records
-
-
[email protected]("mode,available", [("cloud", False), ("local_external", False), ("local_embedded", True), ("local_embedded", False)])
-def test_provider_unavailable_reason(side_root, monkeypatch, mode, available):
- import plugins.memory.hindsight as hs
-
- monkeypatch.setattr(hs, "_load_config", lambda: {"mode": mode})
- def probe():
- assert mode == "local_embedded"
- return available, "NumPy SIMD unavailable"
- monkeypatch.setattr(hs, "_check_local_runtime", probe)
- reason = hs.HindsightMemoryProvider().unavailable_reason()
- if mode != "local_embedded" or available:
- assert reason == ""
- else:
- assert reason == reason.strip()
- assert "NumPy SIMD unavailable" in reason and "hermes memory setup" in reason
- assert str(side_root) in reason
- assert all(requirement in reason for requirement in rt._REQUIREMENTS)
- assert "uv pip install --python" not in reason
-
-
-def test_missing_side_environment_never_starts_daemon(side_root):
- ok, reason = rt.check_local_runtime()
- assert not ok and "hermes memory setup" in reason and str(side_root) in reason
- with pytest.raises(RuntimeError, match="hermes memory setup"):
- rt.ensure_daemon_and_url({})
diff --git a/tests/plugins/memory/test_hindsight_env_perms.py b/tests/plugins/memory/test_hindsight_env_perms.py
deleted file mode 100644
index a68e678f694..00000000000
--- a/tests/plugins/memory/test_hindsight_env_perms.py
+++ /dev/null
@@ -1,145 +0,0 @@
-"""Regression tests: the embedded Hindsight profile env file carries the
-plaintext ``HINDSIGHT_API_LLM_API_KEY`` and must be created/kept owner-only
-(0600), and must not survive a failed post-write permission validation.
-"""
-
-import os
-import stat
-from pathlib import Path
-
-import pytest
-
-from plugins.memory.hindsight import (
- _embedded_profile_env_path,
- _materialize_embedded_profile_env,
-)
-from plugins.memory.hindsight.embedded import _build_embedded_profile_env, _may_rewrite_profile_env
-
-
[email protected](autouse=True)
-def _isolated_home(tmp_path, monkeypatch):
- isolated_home = tmp_path / "user-home"
- monkeypatch.setattr(Path, "home", classmethod(lambda cls: isolated_home))
- return isolated_home
-
-
-_CONFIG = {
- "profile": "hermes",
- "llm_provider": "openai",
- "llm_model": "gpt-4o-mini",
-}
-
-
[email protected]("posix") # POSIX mode bits are not enforced on Windows
-def test_fresh_profile_env_is_owner_only_despite_permissive_umask():
- old_umask = os.umask(0o022)
- try:
- profile_env = _materialize_embedded_profile_env(
- _CONFIG, llm_api_key="sk-hindsight-secret"
- )
- finally:
- os.umask(old_umask)
-
- assert profile_env.exists()
- assert stat.S_IMODE(profile_env.stat().st_mode) == 0o600
- assert "HINDSIGHT_API_LLM_API_KEY=sk-hindsight-secret\n" in profile_env.read_text(
- encoding="utf-8"
- )
-
-
[email protected]("posix") # POSIX mode bits are not enforced on Windows
-def test_rewrite_tightens_existing_world_readable_profile_env():
- profile_env = _embedded_profile_env_path(_CONFIG)
- profile_env.parent.mkdir(parents=True)
- profile_env.write_text("HINDSIGHT_API_LLM_API_KEY=stale\n", encoding="utf-8")
- os.chmod(profile_env, 0o644)
-
- _materialize_embedded_profile_env(_CONFIG, llm_api_key="sk-current")
-
- assert stat.S_IMODE(profile_env.stat().st_mode) == 0o600
- assert "HINDSIGHT_API_LLM_API_KEY=sk-current\n" in profile_env.read_text(
- encoding="utf-8"
- )
-
-
[email protected]("posix") # POSIX mode bits are not enforced on Windows
-def test_secret_file_removed_when_permission_validation_fails(monkeypatch):
- """If the post-write permission check cannot verify 0600, the plaintext
- key file must not be left behind."""
- import plugins.memory.hindsight.embedded as hs_embedded
-
- def _fail_validation(profile_env):
- raise PermissionError(f"not owner-only: {profile_env}")
-
- monkeypatch.setattr(hs_embedded, "_validate_profile_env_permissions", _fail_validation)
-
- with pytest.raises(PermissionError):
- _materialize_embedded_profile_env(_CONFIG, llm_api_key="sk-doomed")
-
- assert not _embedded_profile_env_path(_CONFIG).exists(), (
- "secret env file must be cleaned up when validation fails"
- )
-
-
[email protected]("posix") # POSIX mode bits are not enforced on Windows
-def test_scopeless_worker_reuses_on_disk_key(monkeypatch):
- """Durability core: with no secret scope, the key resolves from disk.
-
- The daemon-start worker usually has no scope; without the disk fallback
- the client would be built keyless and the upstream manager merge
- (ensure_running -> _register_profile -> create_profile rewrite) would
- overwrite the file's good key with emptiness.
- """
- from agent import secret_scope
-
- profile_env = _embedded_profile_env_path(_CONFIG)
- profile_env.parent.mkdir(parents=True)
- profile_env.write_text(
- "HINDSIGHT_API_LLM_PROVIDER=openai\n"
- "HINDSIGHT_API_LLM_API_KEY=sk-test-live-key\n"
- "HINDSIGHT_API_LLM_MODEL=gpt-4o-mini\n"
- "HINDSIGHT_API_LOG_LEVEL=info\n",
- encoding="utf-8",
- )
- os.chmod(profile_env, 0o600)
-
- token = secret_scope.set_secret_scope(None)
- monkeypatch.setattr(secret_scope, "_MULTIPLEX_ACTIVE", True)
- monkeypatch.delenv("HINDSIGHT_API_LLM_API_KEY", raising=False)
- try:
- from plugins.memory.hindsight.embedded import _embedded_llm_api_key
-
- assert _embedded_llm_api_key(_CONFIG) == "sk-test-live-key"
- # ...so the build carries a key and the rewrite gate passes.
- assert _build_embedded_profile_env(_CONFIG)["HINDSIGHT_API_LLM_API_KEY"] == "sk-test-live-key"
- assert _may_rewrite_profile_env(_CONFIG) is True
- finally:
- secret_scope.reset_secret_scope(token)
-
-
-
-
-def test_rewrite_allowed_when_build_carries_key():
- """A build WITH key material (rotation, model drift) must still rewrite."""
- profile_env = _embedded_profile_env_path(_CONFIG)
- profile_env.parent.mkdir(parents=True)
- profile_env.write_text("HINDSIGHT_API_LLM_API_KEY=sk-old\n", encoding="utf-8")
-
- cfg = dict(_CONFIG, llm_api_key="sk-new")
- assert _may_rewrite_profile_env(cfg) is True
- _materialize_embedded_profile_env(cfg)
- assert "HINDSIGHT_API_LLM_API_KEY=sk-new\n" in profile_env.read_text(encoding="utf-8")
-
-
-def test_api_prefixed_vault_name_resolves(monkeypatch):
- """The vault item is HINDSIGHT_API_LLM_API_KEY; the wizard name alone misses."""
- from agent import secret_scope
- import plugins.memory.hindsight.embedded as hs_embedded
-
- token = secret_scope.set_secret_scope({"HINDSIGHT_API_LLM_API_KEY": "sk-test-live-key"})
- monkeypatch.delenv("HINDSIGHT_LLM_API_KEY", raising=False)
- monkeypatch.delenv("HINDSIGHT_API_LLM_API_KEY", raising=False)
- try:
- assert hs_embedded._embedded_llm_api_key(_CONFIG) == "sk-test-live-key"
- finally:
- secret_scope.reset_secret_scope(token)
diff --git a/tests/plugins/memory/test_hindsight_provider.py b/tests/plugins/memory/test_hindsight_provider.py
deleted file mode 100644
index 093d4f4bebc..00000000000
--- a/tests/plugins/memory/test_hindsight_provider.py
+++ /dev/null
@@ -1,1718 +0,0 @@
-"""Tests for the Hindsight memory provider plugin.
-
-Tests cover config loading, tool handlers (tags, max_tokens, types),
-prefetch (auto_recall, preamble, query truncation), sync_turn (auto_retain,
-turn counting, tags), and schema completeness.
-"""
-
-import importlib.util
-import json
-import os
-import re
-import stat
-import sys
-import threading
-import time
-from datetime import datetime
-from pathlib import Path
-from types import ModuleType, SimpleNamespace
-from unittest.mock import AsyncMock, MagicMock
-from zoneinfo import ZoneInfo
-
-import pytest
-
-from hermes_cli.memory_setup import _CANCELLED
-from plugins.memory.hindsight import (
- HindsightMemoryProvider,
- RECALL_SCHEMA,
- REFLECT_SCHEMA,
- RETAIN_SCHEMA,
- _load_config,
- _load_simple_env,
- _build_embedded_profile_env,
- _normalize_observation_scopes,
- _normalize_retain_tags,
- _resolve_bank_id_template,
- _WRITER_SENTINEL,
-)
-from plugins.memory.hindsight.settings import _sanitize_bank_segment
-
-
-# ---------------------------------------------------------------------------
-# Fixtures
-# ---------------------------------------------------------------------------
-
-
[email protected](autouse=True)
-def _clean_env(tmp_path, monkeypatch):
- """Ensure no stale env vars or Windows home state leak between tests."""
- for key in (
- "HINDSIGHT_API_KEY", "HINDSIGHT_API_URL", "HINDSIGHT_BANK_ID",
- "HINDSIGHT_BUDGET", "HINDSIGHT_MODE", "HINDSIGHT_TIMEOUT",
- "HINDSIGHT_IDLE_TIMEOUT", "HINDSIGHT_LLM_API_KEY",
- "HINDSIGHT_RETAIN_TAGS", "HINDSIGHT_RETAIN_OBSERVATION_SCOPES",
- "HINDSIGHT_RETAIN_SOURCE",
- "HINDSIGHT_RETAIN_USER_PREFIX", "HINDSIGHT_RETAIN_ASSISTANT_PREFIX",
- ):
- monkeypatch.delenv(key, raising=False)
-
- # On Windows pathlib.Path.home() resolves USERPROFILE/HOMEDRIVE+HOMEPATH,
- # not the POSIX HOME alias that these tests historically monkeypatched.
- # Patch the actual API and keep all legacy profile writes in tmp_path.
- isolated_home = tmp_path / "user-home"
- monkeypatch.setattr(Path, "home", classmethod(lambda cls: isolated_home))
-
- # These tests provide client doubles, so they must not attempt a network
- # install merely because the optional SDK is absent from the test env.
- monkeypatch.setattr("tools.lazy_deps.ensure", lambda *args, **kwargs: None)
-
- # The retain-operation path imports this exception solely to classify a
- # fake client's response. Supply the smallest matching SDK surface so the
- # mocked tests remain runnable without the optional Hindsight extra.
- # Only when the real SDK is absent: shadowing an installed SDK with a
- # fake (no ``__path__``) breaks ``import hindsight_client`` and turns the
- # pinned-client test into a permanent skip.
- if importlib.util.find_spec("hindsight_client_api") is not None:
- return
- client_api = ModuleType("hindsight_client_api")
- exceptions = ModuleType("hindsight_client_api.exceptions")
-
- class NotFoundException(Exception):
- def __init__(self, *args, **kwargs):
- super().__init__(*args)
-
- exceptions.NotFoundException = NotFoundException
- client_api.exceptions = exceptions
- monkeypatch.setitem(sys.modules, "hindsight_client_api", client_api)
- monkeypatch.setitem(sys.modules, "hindsight_client_api.exceptions", exceptions)
-
-
-def _make_mock_client():
- """Create a mock Hindsight client with async methods."""
- async def _aretain(
- bank_id,
- content,
- timestamp=None,
- context=None,
- document_id=None,
- metadata=None,
- entities=None,
- tags=None,
- update_mode=None,
- retain_async=None,
- ):
- return SimpleNamespace(ok=True)
-
- client = MagicMock()
- client.aretain = AsyncMock(side_effect=_aretain)
- client.arecall = AsyncMock(
- return_value=SimpleNamespace(
- results=[
- SimpleNamespace(text="Memory 1"),
- SimpleNamespace(text="Memory 2"),
- ]
- )
- )
- client.areflect = AsyncMock(
- return_value=SimpleNamespace(text="Synthesized answer")
- )
- client.aretain_batch = AsyncMock()
- client.aclose = AsyncMock()
- return client
-
-
-def _provider_for_mode(tmp_path, monkeypatch, mode: str):
- """Create an initialized provider without pre-seeding its client."""
- config = {
- "mode": mode,
- "apiKey": "test-key",
- "api_url": "http://localhost:9999",
- "bank_id": "test-bank",
- "budget": "mid",
- "memory_mode": "hybrid",
- }
- config_path = tmp_path / "hindsight" / "config.json"
- config_path.parent.mkdir(parents=True, exist_ok=True)
- config_path.write_text(json.dumps(config))
-
- monkeypatch.setattr(
- "plugins.memory.hindsight.get_hermes_home", lambda: tmp_path
- )
-
- provider = HindsightMemoryProvider()
- provider.initialize(session_id="test-session", hermes_home=str(tmp_path), platform="cli")
- return provider
-
-
-def test_initialize_does_not_upgrade_an_old_client(tmp_path, monkeypatch):
- calls = []
- monkeypatch.setattr("importlib.metadata.version", lambda name: "0.0.1")
- monkeypatch.setattr("pm.sync_venv", lambda *args, **kwargs: calls.append((args, kwargs)))
- provider = _provider_for_mode(tmp_path, monkeypatch, "cloud")
- assert provider._session_id == "test-session"
- assert calls == [], "provider initialization must not replace the process dependency generation"
-
-
-def _assert_cloud_client_lazy_installed_before_import(tmp_path, monkeypatch, mode: str):
- """Cloud/local-external clients must ensure lazy deps before importing."""
- import builtins
-
- provider = _provider_for_mode(tmp_path, monkeypatch, mode)
- ensure_calls = []
-
- def fake_ensure(extra):
- ensure_calls.append(extra)
-
- class FakeHindsight:
- def __init__(self, **kwargs):
- self.kwargs = kwargs
-
- real_import = builtins.__import__
-
- def guarded_import(name, globals=None, locals=None, fromlist=(), level=0):
- if name == "hindsight_client":
- if ensure_calls != ["hindsight"]:
- raise ModuleNotFoundError("No module named 'hindsight_client'")
- return SimpleNamespace(Hindsight=FakeHindsight)
- return real_import(name, globals, locals, fromlist, level)
-
- monkeypatch.setattr("pm.ensure_import", fake_ensure)
- monkeypatch.setattr(builtins, "__import__", guarded_import)
-
- client = provider._get_client()
-
- assert ensure_calls == ["hindsight"]
- assert isinstance(client, FakeHindsight)
- assert client.kwargs == {
- "base_url": "http://localhost:9999",
- "timeout": 120.0,
- "api_key": "test-key",
- }
-
-
-class _FakeSessionDB:
- def __init__(self, messages=None):
- self._messages = list(messages or [])
-
- def get_messages_as_conversation(self, session_id):
- return list(self._messages)
-
-
-def provider(tmp_path, monkeypatch):
- """Create an initialized HindsightMemoryProvider with a mock client."""
- config = {
- "mode": "cloud",
- "apiKey": "test-key",
- "api_url": "http://localhost:9999",
- "bank_id": "test-bank",
- "budget": "mid",
- "memory_mode": "hybrid",
- }
- config_path = tmp_path / "hindsight" / "config.json"
- config_path.parent.mkdir(parents=True, exist_ok=True)
- config_path.write_text(json.dumps(config))
-
- monkeypatch.setattr(
- "plugins.memory.hindsight.get_hermes_home", lambda: tmp_path
- )
-
- p = HindsightMemoryProvider()
- p.initialize(session_id="test-session", hermes_home=str(tmp_path), platform="cli")
- p._client = _make_mock_client()
- return p
-
-
-def provider_with_config(tmp_path, monkeypatch):
- """Create a provider factory that accepts custom config overrides."""
- def _make(**overrides):
- config = {
- "mode": "cloud",
- "apiKey": "test-key",
- "api_url": "http://localhost:9999",
- "bank_id": "test-bank",
- "budget": "mid",
- "memory_mode": "hybrid",
- }
- config.update(overrides)
- config_path = tmp_path / "hindsight" / "config.json"
- config_path.parent.mkdir(parents=True, exist_ok=True)
- config_path.write_text(json.dumps(config))
-
- monkeypatch.setattr(
- "plugins.memory.hindsight.get_hermes_home", lambda: tmp_path
- )
-
- p = HindsightMemoryProvider()
- p.initialize(session_id="test-session", hermes_home=str(tmp_path), platform="cli")
- p._client = _make_mock_client()
- return p
- return _make
-
-
-def test_normalize_retain_tags_accepts_csv_and_dedupes():
- assert _normalize_retain_tags("agent:fakeassistantname, source_system:hermes-agent, agent:fakeassistantname") == [
- "agent:fakeassistantname",
- "source_system:hermes-agent",
- ]
-
-
-# ---------------------------------------------------------------------------
-# Schema tests
-# ---------------------------------------------------------------------------
-
-
-class TestSchemas:
- def test_retain_schema_has_content(self):
- assert RETAIN_SCHEMA["name"] == "hindsight_retain"
- assert "content" in RETAIN_SCHEMA["parameters"]["properties"]
- assert "tags" in RETAIN_SCHEMA["parameters"]["properties"]
- assert "content" in RETAIN_SCHEMA["parameters"]["required"]
-
-
- def test_get_tool_schemas_returns_three(self, provider):
- schemas = provider.get_tool_schemas()
- assert len(schemas) == 3
- names = {s["name"] for s in schemas}
- assert names == {"hindsight_retain", "hindsight_recall", "hindsight_reflect"}
-
- def test_context_mode_returns_no_tools(self, provider_with_config):
- p = provider_with_config(memory_mode="context")
- assert p.get_tool_schemas() == []
-
-
-# ---------------------------------------------------------------------------
-# Config tests
-# ---------------------------------------------------------------------------
-
-
-class TestConfig:
- def test_cloud_client_lazy_installs_dependency_before_import(self, tmp_path, monkeypatch):
- _assert_cloud_client_lazy_installed_before_import(tmp_path, monkeypatch, "cloud")
-
-
- def test_default_values(self, provider):
- assert provider._auto_retain is True
- assert provider._auto_recall is True
- assert provider._retain_every_n_turns == 1
- assert provider._recall_max_tokens == 4096
- assert provider._recall_max_input_chars == 800
- assert provider._tags is None
- assert provider._observation_scopes is None
- assert provider._recall_tags is None
- # Default recall narrowed to observation-only; world/experience are
- # aggregate facts that often crowd out concrete-event signal during
- # auto-recall. Users opt back in via the recall_types config key.
- assert provider._recall_types == ["observation"]
- assert provider._bank_mission == ""
- assert provider._bank_retain_mission is None
- assert provider._retain_context == "conversation between Hermes Agent and the User"
-
- def test_recall_types_default_is_observation_only(self, provider):
- """Auto-recall must filter to observation by default."""
- assert provider._recall_types == ["observation"]
-
-
- def test_observation_scopes_keyword_config(self, provider_with_config):
- p = provider_with_config(observation_scopes="per_tag")
- assert p._observation_scopes == "per_tag"
-
-
- def test_custom_config_values(self, provider_with_config):
- p = provider_with_config(
- retain_tags=["tag1", "tag2"],
- retain_source="hermes",
- retain_user_prefix="User (fakeusername)",
- retain_assistant_prefix="Assistant (fakeassistantname)",
- recall_tags=["recall-tag"],
- recall_tags_match="all",
- auto_retain=False,
- auto_recall=False,
- retain_every_n_turns=3,
- retain_context="custom-ctx",
- bank_retain_mission="Extract key facts",
- recall_max_tokens=2048,
- recall_types=["world", "experience"],
- recall_prompt_preamble="Custom preamble:",
- recall_max_input_chars=500,
- bank_mission="Test agent mission",
- )
- assert p._tags == ["tag1", "tag2"]
- assert p._retain_tags == ["tag1", "tag2"]
- assert p._retain_source == "hermes"
- assert p._retain_user_prefix == "User (fakeusername)"
- assert p._retain_assistant_prefix == "Assistant (fakeassistantname)"
- assert p._recall_tags == ["recall-tag"]
- assert p._recall_tags_match == "all"
- assert p._auto_retain is False
- assert p._auto_recall is False
- assert p._retain_every_n_turns == 3
- assert p._retain_context == "custom-ctx"
- assert p._bank_retain_mission == "Extract key facts"
- assert p._recall_max_tokens == 2048
- assert p._recall_types == ["world", "experience"]
- assert p._recall_prompt_preamble == "Custom preamble:"
- assert p._recall_max_input_chars == 500
- assert p._bank_mission == "Test agent mission"
-
- def test_retain_source_defaults_empty(self, provider):
- # Opt-in per AGENTS.md: no attribution tag ships by default.
- assert provider._retain_source == ""
-
- def test_retain_source_absent_from_metadata_by_default(self, provider):
- # metadata.source is stamped only when the user sets retain_source.
- meta = provider._build_metadata(message_count=2, turn_index=1)
- assert "source" not in meta
-
- def test_retain_source_user_override_wins(self, provider_with_config):
- # Users can still opt in explicitly (config key / env var).
- p = provider_with_config(retain_source="cogoport")
- assert p._retain_source == "cogoport"
- assert p._build_metadata(message_count=2, turn_index=1)["source"] == "cogoport"
-
- def test_embedded_profile_env_includes_idle_timeout_from_config(self):
- env = _build_embedded_profile_env({
- "llm_provider": "openai",
- "llm_model": "gpt-4o-mini",
- "idle_timeout": 0,
- })
-
- assert env["HINDSIGHT_EMBED_DAEMON_IDLE_TIMEOUT"] == "0"
-
-
- def test_get_client_connects_http_client_to_sideenv_daemon(self, monkeypatch):
- captured = {}
-
- class FakeHindsight:
- def __init__(self, **kwargs):
- captured.update(kwargs)
-
- monkeypatch.setitem(sys.modules, "hindsight_client", SimpleNamespace(Hindsight=FakeHindsight))
- # The daemon URL comes from the side env; no port is hardcoded here.
- side_calls = []
-
- def fake_start(cfg, **kwargs):
- side_calls.append(cfg)
- return "http://127.0.0.1:9157"
-
- monkeypatch.setattr("plugins.memory.hindsight._start_sideenv_daemon", fake_start)
- # The lazy client install is the pm boundary, not what this test exercises.
- monkeypatch.setattr("plugins.memory.hindsight._ensure_client_dependency", lambda: None)
-
- monkeypatch.setattr("plugins.memory.hindsight._materialize_embedded_profile_env", lambda *a: None)
- p = HindsightMemoryProvider()
- p._mode = "local_embedded"
- p._config = {
- "profile": "hermes",
- "llm_provider": "openai_compatible",
- "llm_api_key": "test-key",
- "llm_model": "test-model",
- "idle_timeout": 0,
- }
- p._llm_base_url = "http://localhost:8060/v1"
-
- p._get_client()
-
- # The side-env daemon manager receives the config (LLM keys ride the
- # materialized profile .env, not the client); Hermes talks HTTP.
- assert side_calls == [p._config]
- assert captured["base_url"] == "http://127.0.0.1:9157"
- assert p._api_url == "http://127.0.0.1:9157"
-
-
-class TestPostSetup:
- def test_setup_cancel_at_mode_picker_writes_nothing(self, tmp_path, monkeypatch):
- hermes_home = tmp_path / "hermes-home"
- user_home = tmp_path / "user-home"
- user_home.mkdir()
- monkeypatch.setenv("HOME", str(user_home))
- monkeypatch.setattr("plugins.memory.hindsight.get_hermes_home", lambda: hermes_home)
-
- save_config = MagicMock()
- which = MagicMock(return_value="/usr/bin/uv")
- run = MagicMock()
- monkeypatch.setattr("hermes_cli.memory_setup._curses_select", lambda *args, **kwargs: _CANCELLED)
- monkeypatch.setattr("shutil.which", which)
- monkeypatch.setattr("subprocess.run", run)
- monkeypatch.setattr("builtins.input", MagicMock(side_effect=AssertionError("prompt should not run")))
- monkeypatch.setattr("getpass.getpass", MagicMock(side_effect=AssertionError("prompt should not run")))
- monkeypatch.setattr("hermes_cli.config.save_config", save_config)
-
- provider = HindsightMemoryProvider()
- provider.post_setup(str(hermes_home), {"memory": {"provider": "builtin"}})
-
- save_config.assert_not_called()
- which.assert_not_called()
- run.assert_not_called()
- assert not (hermes_home / ".env").exists()
- assert not (hermes_home / "hindsight" / "config.json").exists()
- assert not (user_home / ".hindsight" / "profiles" / "hermes.env").exists()
-
-
- def test_local_embedded_setup_materializes_profile_env(self, tmp_path, monkeypatch):
- hermes_home = tmp_path / "hermes-home"
- user_home = tmp_path / "user-home"
- user_home.mkdir()
- monkeypatch.setenv("HOME", str(user_home))
-
- monkeypatch.setattr("plugins.memory.hindsight.setup._sync_client_dependency", lambda: True)
- monkeypatch.setattr("plugins.memory.hindsight.setup._install_embedded_runtime", lambda: True)
- selections = iter([1, 0]) # local_embedded, openai
- monkeypatch.setattr("hermes_cli.memory_setup._curses_select", lambda *args, **kwargs: next(selections))
- monkeypatch.setattr("shutil.which", lambda name: None)
- monkeypatch.setattr("builtins.input", lambda prompt="": "")
- monkeypatch.setattr("sys.stdin.isatty", lambda: True)
- monkeypatch.setattr("getpass.getpass", lambda prompt="": "sk-local-test")
- saved_configs = []
- monkeypatch.setattr("hermes_cli.config.save_config", lambda cfg: saved_configs.append(cfg.copy()))
-
- provider = HindsightMemoryProvider()
- provider.post_setup(str(hermes_home), {"memory": {}})
-
- assert saved_configs[-1]["memory"]["provider"] == "hindsight"
- env_text = (hermes_home / ".env").read_text()
- assert "HINDSIGHT_LLM_API_KEY=sk-local-test\n" in env_text
- assert "HINDSIGHT_TIMEOUT=120\n" in env_text
- assert "HINDSIGHT_IDLE_TIMEOUT=300\n" in env_text
-
- profile_env = user_home / ".hindsight" / "profiles" / "hermes.env"
- assert profile_env.exists()
- assert profile_env.read_text() == (
- "HINDSIGHT_API_LLM_PROVIDER=openai\n"
- "HINDSIGHT_API_LLM_API_KEY=sk-local-test\n"
- "HINDSIGHT_API_LLM_MODEL=gpt-4o-mini\n"
- "HINDSIGHT_API_LOG_LEVEL=info\n"
- "HINDSIGHT_EMBED_DAEMON_IDLE_TIMEOUT=300\n"
- )
-
-
-# ---------------------------------------------------------------------------
-# Tool handler tests
-# ---------------------------------------------------------------------------
-
-
-class TestToolHandlers:
- def test_retain_success(self, provider):
- result = json.loads(provider.handle_tool_call(
- "hindsight_retain", {"content": "user likes dark mode"}
- ))
- assert result["result"] == "Memory stored successfully."
- provider._client.aretain_batch.assert_called_once()
- call_kwargs = provider._client.aretain_batch.call_args.kwargs
- assert call_kwargs["bank_id"] == "test-bank"
- item = call_kwargs["items"][0]
- assert item["content"] == "user likes dark mode"
- # bank_id/retain_async are call-level args, never item keys.
- assert "bank_id" not in item
- assert "retain_async" not in item
-
- def test_retain_defaults_item_timestamp_when_no_occurred_at(self, provider, monkeypatch):
- event_time = datetime(2026, 8, 24, 9, 30, tzinfo=ZoneInfo("America/Los_Angeles"))
- monkeypatch.setattr("plugins.memory.hindsight._hermes_now", lambda: event_time)
- result = json.loads(provider.handle_tool_call(
- "hindsight_retain", {"content": "user likes dark mode"}
- ))
- assert result["result"] == "Memory stored successfully."
- item = provider._client.aretain_batch.call_args.kwargs["items"][0]
- # Non-temporal retains still carry a defaulted event timestamp so the
- # server can resolve any relative time phrases (#93568).
- assert item["timestamp"] == event_time.isoformat(timespec="seconds")
-
- def test_retain_threads_explicit_occurred_at_into_item_timestamp(self, provider):
- result = json.loads(provider.handle_tool_call(
- "hindsight_retain",
- {"content": "user visited Paris", "occurred_at": "2026-03-03"},
- ))
- assert result["result"] == "Memory stored successfully."
- item = provider._client.aretain_batch.call_args.kwargs["items"][0]
- assert item["timestamp"] == "2026-03-03"
-
- def test_retain_ignores_blank_occurred_at(self, provider, monkeypatch):
- event_time = datetime(2026, 8, 24, 9, 30, tzinfo=ZoneInfo("America/Los_Angeles"))
- monkeypatch.setattr("plugins.memory.hindsight._hermes_now", lambda: event_time)
- json.loads(provider.handle_tool_call(
- "hindsight_retain", {"content": "hello", "occurred_at": " "}
- ))
- item = provider._client.aretain_batch.call_args.kwargs["items"][0]
- assert item["timestamp"] == event_time.isoformat(timespec="seconds")
-
- def test_build_retain_kwargs_accepts_explicit_occurred_at(self, provider):
- item = provider._build_retain_kwargs("dinner with Sam", occurred_at="2026-08-20T19:00:00+02:00")
- assert item["timestamp"] == "2026-08-20T19:00:00+02:00"
-
- def test_retain_schema_exposes_occurred_at(self):
- from plugins.memory.hindsight import RETAIN_SCHEMA
-
- props = RETAIN_SCHEMA["parameters"]["properties"]
- assert "occurred_at" in props
- assert props["occurred_at"]["type"] == "string"
- # The description must steer the model to pass event times.
- assert "event" in props["occurred_at"]["description"].lower()
- assert "occurred_at" not in RETAIN_SCHEMA["parameters"]["required"]
-
-
- def test_recall_success(self, provider):
- result = json.loads(provider.handle_tool_call(
- "hindsight_recall", {"query": "dark mode"}
- ))
- assert "Memory 1" in result["result"]
- assert "Memory 2" in result["result"]
-
-
- def test_reflect_success(self, provider):
- result = json.loads(provider.handle_tool_call(
- "hindsight_reflect", {"query": "summarize"}
- ))
- assert result["result"] == "Synthesized answer"
-
-
- def test_unknown_tool(self, provider):
- result = json.loads(provider.handle_tool_call(
- "hindsight_unknown", {}
- ))
- assert "error" in result
-
-
- def test_local_embedded_recall_reconnects_after_idle_shutdown(self, provider, monkeypatch):
- first_client = _make_mock_client()
- first_client.arecall.side_effect = RuntimeError("Cannot connect to host 127.0.0.1:8888")
- second_client = _make_mock_client()
- second_client.arecall.return_value = SimpleNamespace(
- results=[SimpleNamespace(text="Recovered memory")]
- )
- clients = iter([first_client, second_client])
-
- provider._mode = "local_embedded"
- provider._client = first_client
- monkeypatch.setattr(provider, "_get_client", lambda: next(clients))
-
- result = json.loads(provider.handle_tool_call(
- "hindsight_recall", {"query": "test"}
- ))
-
- assert result["result"] == "1. Recovered memory"
- assert provider._client is second_client
- first_client.arecall.assert_called_once()
- second_client.arecall.assert_called_once()
-
-
-# ---------------------------------------------------------------------------
-# Prefetch tests
-# ---------------------------------------------------------------------------
-
-
-class TestPrefetch:
- def test_prefetch_returns_empty_when_no_result(self, provider):
- assert provider.prefetch("test") == ""
-
-
- def test_recall_sync_defaults_off(self, provider):
- assert provider._recall_sync is False
-
- def test_recall_sync_recalls_current_query_synchronously(self, provider_with_config):
- # recall_sync=True: prefetch() must do a live recall against the
- # *current* query (not read a previously queued buffer). #5820
- p = provider_with_config(recall_sync=True)
- captured = {}
-
- def _capture_recall(**kwargs):
- captured["query"] = kwargs.get("query", "")
- return SimpleNamespace(results=[SimpleNamespace(text="fresh memory")])
-
- p._client.arecall = AsyncMock(side_effect=_capture_recall)
-
- # Nothing pre-buffered — proves the result comes from a live recall.
- assert p._prefetch_result == ""
- result = p.prefetch("fix tests")
-
- assert captured["query"] == "fix tests" # current query, not ignored
- assert "fresh memory" in result
- p._client.arecall.assert_called_once()
-
- def test_recall_sync_skips_background_queue(self, provider_with_config):
- # With sync recall there's nothing to prime in the background.
- p = provider_with_config(recall_sync=True)
- p.queue_prefetch("anything")
- assert p._prefetch_thread is None
-
- def test_async_default_ignores_current_query_and_reads_buffer(self, provider):
- # Default (recall_sync off): prefetch returns the buffered result and
- # does NOT issue a live recall for the current query.
- provider._prefetch_result = "- buffered from previous turn"
- result = provider.prefetch("a totally different current query")
- assert "buffered from previous turn" in result
- provider._client.arecall.assert_not_called()
-
- def test_queue_prefetch_skipped_in_tools_mode(self, provider_with_config):
- p = provider_with_config(memory_mode="tools")
- p.queue_prefetch("test")
- # Should not start a thread
- assert p._prefetch_thread is None
-
- def test_prefetch_waits_for_pending_retain_before_recall(self, provider):
- """The background prefetch must wait for queued retains to drain so the
- next turn's recall observes the just-completed turn (no retain race)."""
- import threading
-
- order = []
- release = threading.Event()
-
- async def _slow_retain(*args, **kwargs):
- release.wait(timeout=5.0)
- order.append("retain")
-
- async def _recall(**kwargs):
- order.append("recall")
- return SimpleNamespace(results=[SimpleNamespace(text="m")])
-
- provider._client.aretain_batch = AsyncMock(side_effect=_slow_retain)
- provider._client.arecall = AsyncMock(side_effect=_recall)
-
- # Enqueue a slow retain, then immediately queue the next-turn prefetch.
- provider.sync_turn("hello", "world")
- provider.queue_prefetch("next turn query")
-
- # Let the prefetch thread start and reach the drain barrier.
- time.sleep(0.2)
- assert order == [], "recall ran before the pending retain drained"
-
- # Release the retain; the prefetch should now proceed AFTER it.
- release.set()
- if provider._prefetch_thread:
- provider._prefetch_thread.join(timeout=5.0)
- provider._retain_queue.join()
- assert order and order[0] == "retain"
- assert "recall" in order
-
- def test_prefetch_wait_for_retain_can_be_disabled(self, provider_with_config):
- p = provider_with_config(prefetch_waits_for_retain=False)
- p._client = _make_mock_client()
- assert p._prefetch_waits_for_retain is False
-
-
-class TestPrefetchServerRetainVisibility:
- """PR #62871 review follow-up: draining the local writer queue is not a
- read-after-write signal for async retains. With ``retain_async=True`` the
- server accepts the write and returns an ``operation_id`` that stays
- ``pending`` until the write is durable/recall-visible. The background
- prefetch must gate on server-side operation completion, not just the local
- queue, before recalling.
- """
-
- def _client_with_ops(self, statuses):
- """Mock client whose aretain_batch returns an async operation_id and
- whose operations.get_operation_status yields *statuses* in order
- (last value repeats)."""
- client = _make_mock_client()
- client.aretain_batch = AsyncMock(
- return_value=SimpleNamespace(operation_id="op-1", operation_ids=None)
- )
- seq = list(statuses)
-
- async def _status(**kwargs):
- value = seq.pop(0) if len(seq) > 1 else seq[0]
- return SimpleNamespace(status=value)
-
- client.operations = MagicMock()
- client.operations.get_operation_status = AsyncMock(side_effect=_status)
- return client
-
- def test_tracks_async_operation_id_from_retain(self, provider):
- provider._client.aretain_batch = AsyncMock(
- return_value=SimpleNamespace(operation_id="op-async-1", operation_ids=None)
- )
- provider.sync_turn("hello", "world")
- provider._retain_queue.join()
- assert "op-async-1" in provider._pending_retain_ops
-
- def test_tracks_multiple_operation_ids(self, provider):
- provider._client.aretain_batch = AsyncMock(
- return_value=SimpleNamespace(
- operation_id=None, operation_ids=["op-a", "op-b"]
- )
- )
- provider.sync_turn("hello", "world")
- provider._retain_queue.join()
- assert {"op-a", "op-b"} <= provider._pending_retain_ops
-
- def test_sync_retain_tracks_no_ops(self, provider_with_config):
- p = provider_with_config(retain_async=False)
- p._client = _make_mock_client()
- p._client.aretain_batch = AsyncMock(
- return_value=SimpleNamespace(operation_id="op-x", operation_ids=None)
- )
- p.sync_turn("hello", "world")
- p._retain_queue.join()
- # retain_async=False → no server-side op to wait on.
- assert p._pending_retain_ops == set()
-
- def test_prefetch_waits_for_server_completion_before_recall(self, provider):
- """Recall must not run until the tracked async op reports completed."""
- order = []
-
- async def _recall(**kwargs):
- order.append("recall")
- return SimpleNamespace(results=[SimpleNamespace(text="m")])
-
- provider._client = self._client_with_ops(["pending", "pending", "completed"])
- provider._client.arecall = AsyncMock(side_effect=_recall)
-
- provider.sync_turn("hello", "world")
- provider._retain_queue.join()
- assert "op-1" in provider._pending_retain_ops
-
- provider.queue_prefetch("next turn query")
- if provider._prefetch_thread:
- provider._prefetch_thread.join(timeout=5.0)
-
- # Recall ran, the op was polled to completion, and the pending set
- # was cleared (so a later prefetch won't re-poll it).
- assert order == ["recall"]
- assert provider._client.operations.get_operation_status.await_count >= 3
- assert provider._pending_retain_ops == set()
-
- def test_prefetch_proceeds_after_server_wait_timeout(self, provider_with_config):
- """A wedged/never-completing async op must not hang prefetch forever;
- it recalls anyway once the drain budget is exhausted."""
- p = provider_with_config(prefetch_retain_drain_timeout=0.3)
- order = []
-
- async def _recall(**kwargs):
- order.append("recall")
- return SimpleNamespace(results=[SimpleNamespace(text="m")])
-
- p._client = self._client_with_ops(["pending"]) # never completes
- p._client.arecall = AsyncMock(side_effect=_recall)
-
- p.sync_turn("hello", "world")
- p._retain_queue.join()
-
- start = time.monotonic()
- p.queue_prefetch("next turn query")
- if p._prefetch_thread:
- p._prefetch_thread.join(timeout=5.0)
- elapsed = time.monotonic() - start
-
- assert order == ["recall"], "prefetch should recall after the timeout"
- assert elapsed < 3.0, "prefetch must not block well past the drain budget"
-
- def test_timed_out_ops_are_dropped_not_repolled(self, provider_with_config):
- """Ops unresolved at deadline must be EVICTED so a permanently failing
- status endpoint can't make every later prefetch re-burn the full
- timeout on a growing pending set (unbounded session-wide degradation
- + reply-path join penalty)."""
- p = provider_with_config(prefetch_retain_drain_timeout=0.3)
- p._client = self._client_with_ops(["pending"]) # never completes
- p._client.arecall = AsyncMock(
- return_value=SimpleNamespace(results=[SimpleNamespace(text="m")])
- )
-
- p.sync_turn("hello", "world")
- p._retain_queue.join()
- assert p._pending_retain_ops, "op should be tracked before the wait"
-
- # First prefetch burns the budget and must DROP the wedged op.
- p.queue_prefetch("q1")
- if p._prefetch_thread:
- p._prefetch_thread.join(timeout=5.0)
- assert p._pending_retain_ops == set(), (
- "unresolved ops must be evicted at deadline, not retained"
- )
-
- # A later prefetch with nothing pending must be near-instant.
- start = time.monotonic()
- p.queue_prefetch("q2")
- if p._prefetch_thread:
- p._prefetch_thread.join(timeout=5.0)
- assert time.monotonic() - start < 0.25, (
- "second prefetch re-polled dropped ops — eviction regressed"
- )
-
- def test_operation_notfound_treated_as_complete(self, provider):
- """A NotFound (completed+evicted) op is treated as done, not pending."""
- exceptions = pytest.importorskip(
- "hindsight_client_api.exceptions",
- reason="Hindsight SDK is not installed",
- )
- NotFoundException = exceptions.NotFoundException
-
- client = _make_mock_client()
- client.operations = MagicMock()
- client.operations.get_operation_status = AsyncMock(
- side_effect=NotFoundException(status=404, reason="gone")
- )
- provider._client = client
-
- assert provider._is_retain_op_complete("bank", "op-gone") is True
-
- def test_transient_status_error_keeps_waiting(self, provider):
- """A transient status-check error means 'unknown', so keep waiting."""
- client = _make_mock_client()
- client.operations = MagicMock()
- client.operations.get_operation_status = AsyncMock(
- side_effect=RuntimeError("temporary blip")
- )
- provider._client = client
-
- assert provider._is_retain_op_complete("bank", "op-1") is False
-
-
-# ---------------------------------------------------------------------------
-# recall_status (deterministic recall indicator) tests
-# ---------------------------------------------------------------------------
-
-
-class TestRecallStatus:
- def test_none_before_any_prefetch(self, provider):
- # Nothing recalled yet → no indicator.
- assert provider.recall_status() is None
-
- def test_reports_count_after_recall(self, provider):
- # Mock client returns 2 memories; prefetch consumes the block.
- provider.queue_prefetch("test")
- if provider._prefetch_thread:
- provider._prefetch_thread.join(timeout=5.0)
- provider.prefetch("test")
-
- status = provider.recall_status()
- assert status is not None
- assert status.provider_label == "Hindsight"
- assert status.count == 2
-
- def test_reports_count_in_recall_sync_mode(self, provider_with_config):
- # recall_sync path does a live recall inside prefetch() (no background
- # prime) — the indicator must still report the count for that turn.
- p = provider_with_config(recall_sync=True)
- assert p.prefetch("test") # live recall returns the 2 mock memories
- status = p.recall_status()
- assert status is not None
- assert status.count == 2
-
- def test_none_when_recall_returned_nothing(self, provider):
- provider._client.arecall = AsyncMock(
- return_value=SimpleNamespace(results=[])
- )
- provider.queue_prefetch("test")
- if provider._prefetch_thread:
- provider._prefetch_thread.join(timeout=5.0)
- assert provider.prefetch("test") == ""
- assert provider.recall_status() is None
-
- def test_stale_count_cleared_on_empty_turn(self, provider):
- # First turn recalls 2 memories.
- provider.queue_prefetch("test")
- if provider._prefetch_thread:
- provider._prefetch_thread.join(timeout=5.0)
- provider.prefetch("test")
- assert provider.recall_status().count == 2
-
- # Next turn recalls nothing — the prior count must not linger.
- provider._client.arecall = AsyncMock(
- return_value=SimpleNamespace(results=[])
- )
- provider.queue_prefetch("test2")
- if provider._prefetch_thread:
- provider._prefetch_thread.join(timeout=5.0)
- provider.prefetch("test2")
- assert provider.recall_status() is None
-
- def test_suppressed_when_indicator_off(self, provider_with_config):
- p = provider_with_config(recall_indicator=False)
- p.queue_prefetch("test")
- if p._prefetch_thread:
- p._prefetch_thread.join(timeout=5.0)
- p.prefetch("test")
- # Memory was injected, but the indicator is turned off.
- assert p._last_recall_returned is True
- assert p.recall_status() is None
-
- def test_reflect_mode_reports_generic_count(self, provider_with_config):
- p = provider_with_config(recall_prefetch_method="reflect")
- p.queue_prefetch("test")
- if p._prefetch_thread:
- p._prefetch_thread.join(timeout=5.0)
- p.prefetch("test")
- status = p.recall_status()
- assert status is not None
- # Reflect synthesizes across memories → no discrete count (0).
- assert status.count == 0
-
-
-# ---------------------------------------------------------------------------
-# sync_turn tests
-# ---------------------------------------------------------------------------
-
-
-class TestSyncTurn:
- def test_sync_turn_retains_metadata_rich_turn(self, provider_with_config, monkeypatch):
- event_time = datetime(2026, 8, 10, 11, 9, tzinfo=ZoneInfo("Asia/Shanghai"))
- monkeypatch.setattr("plugins.memory.hindsight._hermes_now", lambda: event_time)
- p = provider_with_config(
- retain_tags=["conv", "session1"],
- retain_source="hermes",
- retain_user_prefix="User (fakeusername)",
- retain_assistant_prefix="Assistant (fakeassistantname)",
- )
- p.initialize(
- session_id="session-1",
- platform="discord",
- user_id="fakeusername-123",
- user_name="fakeusername",
- chat_id="1485316232612941897",
- chat_name="fakeassistantname-forums",
- chat_type="thread",
- thread_id="1491249007475949698",
- agent_identity="fakeassistantname",
- )
- p._client = _make_mock_client()
-
- p.sync_turn("hello", "hi there")
- p._retain_queue.join()
-
- p._client.aretain_batch.assert_called_once()
- call_kwargs = p._client.aretain_batch.call_args.kwargs
- assert call_kwargs["bank_id"] == "test-bank"
- assert call_kwargs["document_id"].startswith("session-1-")
- assert call_kwargs["retain_async"] is True
- assert len(call_kwargs["items"]) == 1
- item = call_kwargs["items"][0]
- assert item["context"] == "conversation between Hermes Agent and the User"
- assert item["tags"] == ["conv", "session1", "session:session-1"]
- content = json.loads(item["content"])
- assert len(content) == 1
- assert content[0][0]["role"] == "user"
- assert content[0][0]["content"] == "User (fakeusername): hello"
- assert content[0][1]["role"] == "assistant"
- assert content[0][1]["content"] == "Assistant (fakeassistantname): hi there"
- assert item["metadata"]["source"] == "hermes"
- assert item["metadata"]["session_id"] == "session-1"
- assert item["metadata"]["platform"] == "discord"
- assert item["metadata"]["user_id"] == "fakeusername-123"
- assert item["metadata"]["user_name"] == "fakeusername"
- assert item["metadata"]["chat_id"] == "1485316232612941897"
- assert item["metadata"]["chat_name"] == "fakeassistantname-forums"
- assert item["metadata"]["chat_type"] == "thread"
- assert item["metadata"]["thread_id"] == "1491249007475949698"
- assert item["metadata"]["agent_identity"] == "fakeassistantname"
- assert item["metadata"]["turn_index"] == "1"
- assert item["metadata"]["message_count"] == "2"
- assert content[0][0]["timestamp"] == event_time.isoformat(timespec="seconds")
- assert content[0][1]["timestamp"] == event_time.isoformat(timespec="seconds")
- assert re.fullmatch(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z", item["metadata"]["retained_at"])
- assert item["timestamp"] == event_time.isoformat(timespec="seconds")
-
- def test_retain_timestamp_normalizes_a_naive_clock(self, provider, monkeypatch):
- event_time = datetime(2026, 8, 10, 11, 9)
- monkeypatch.setattr("plugins.memory.hindsight._hermes_now", lambda: event_time)
-
- timestamp = provider._build_retain_kwargs("hello")["timestamp"]
- parsed = datetime.fromisoformat(timestamp)
-
- assert parsed.tzinfo is not None
- assert parsed.utcoffset() is not None
-
- @pytest.mark.asyncio
- async def test_retain_timestamp_is_serialized_by_pinned_client(self, provider):
- hindsight_client = pytest.importorskip(
- "hindsight_client", reason="pinned hindsight-client SDK not installed"
- )
- Hindsight = hindsight_client.Hindsight
-
- item = provider._build_retain_kwargs("hello")
- item.pop("bank_id", None)
- item.pop("retain_async", None)
-
- client = Hindsight(base_url="http://localhost:9999", api_key="test-key")
- client._memory_api.retain_memories = AsyncMock(return_value=SimpleNamespace(ok=True))
- try:
- await client.aretain_batch(bank_id="test-bank", items=[item])
- call = client._memory_api.retain_memories.await_args
- assert call is not None
- request = call.args[1]
- assert request.to_dict()["items"][0]["timestamp"] == item["timestamp"]
- finally:
- await client.aclose()
-
-
- def test_resume_creates_new_document(self, tmp_path, monkeypatch):
- """Resuming a session (re-initializing) gets a new document_id
- so previously stored content is not overwritten."""
- config = {"mode": "cloud", "apiKey": "k", "api_url": "http://x", "bank_id": "b"}
- config_path = tmp_path / "hindsight" / "config.json"
- config_path.parent.mkdir(parents=True, exist_ok=True)
- config_path.write_text(json.dumps(config))
- monkeypatch.setattr("plugins.memory.hindsight.get_hermes_home", lambda: tmp_path)
-
- p1 = HindsightMemoryProvider()
- p1.initialize(session_id="resumed-session", hermes_home=str(tmp_path), platform="cli")
-
- # Sleep just enough that the microsecond timestamp differs
- import time
- time.sleep(0.001)
-
- p2 = HindsightMemoryProvider()
- p2.initialize(session_id="resumed-session", hermes_home=str(tmp_path), platform="cli")
-
- # Same session, but each process gets its own document_id
- assert p1._document_id != p2._document_id
- assert p1._document_id.startswith("resumed-session-")
- assert p2._document_id.startswith("resumed-session-")
-
-
-# ---------------------------------------------------------------------------
-# retain indicator ("saving to memory") tests
-# ---------------------------------------------------------------------------
-
-
-class TestRetainIndicator:
- _SAVING = "👁️ Hindsight — saving to memory…"
-
- def test_emits_saving_on_dispatch(self, provider_with_config):
- calls = []
- p = provider_with_config(retain_async=False)
- p._status_callback = calls.append
- p.sync_turn("hello", "hi")
- p._retain_queue.join()
- assert self._SAVING in calls
-
- def test_suppressed_when_indicator_off(self, provider_with_config):
- calls = []
- p = provider_with_config(retain_indicator=False, retain_async=False)
- p._status_callback = calls.append
- p.sync_turn("hello", "hi")
- p._retain_queue.join()
- assert calls == []
-
- def test_no_emit_when_auto_retain_off(self, provider_with_config):
- calls = []
- p = provider_with_config(auto_retain=False)
- p._status_callback = calls.append
- p.sync_turn("hello", "hi") # returns early — nothing dispatched
- assert calls == []
-
- def test_no_emit_on_buffered_turn(self, provider_with_config):
- # retain_every_n_turns=2: turn 1 buffers (no write, no line),
- # turn 2 flushes (one line) — "saving" only fires on a real write.
- calls = []
- p = provider_with_config(retain_every_n_turns=2, retain_async=False)
- p._status_callback = calls.append
- p.sync_turn("t1-u", "t1-a")
- assert calls == []
- p.sync_turn("t2-u", "t2-a")
- p._retain_queue.join()
- assert calls == [self._SAVING]
-
- def test_no_crash_without_callback(self, provider_with_config):
- p = provider_with_config(retain_async=False)
- assert p._status_callback is None
- p.sync_turn("hello", "hi") # must not raise
- p._retain_queue.join()
-
- def test_status_callback_wired_from_initialize(self, tmp_path, monkeypatch):
- cb = lambda _m: None
- p = _provider_for_mode(tmp_path, monkeypatch, "cloud")
- p.initialize(session_id="s", hermes_home=str(tmp_path), status_callback=cb)
- assert p._status_callback is cb
-
-
-# ---------------------------------------------------------------------------
-# Shutdown / writer tests
-# ---------------------------------------------------------------------------
-
-
-class TestShutdownRace:
- def test_sync_turn_uses_single_writer_thread(self, provider):
- """All retains run through one long-lived writer thread."""
- provider.sync_turn("a", "b")
- provider._retain_queue.join()
- first_writer = provider._writer_thread
- assert first_writer is not None
- assert first_writer.is_alive()
-
- provider.sync_turn("c", "d")
- provider._retain_queue.join()
- # Same thread reused — no ad-hoc thread per call.
- assert provider._writer_thread is first_writer
- assert provider._client.aretain_batch.call_count == 2
-
-
- def test_shutdown_drains_pending_retains(self, provider):
- """Shutdown must wait for queued retains to complete, not abandon them.
-
- Otherwise the LAST in-flight turn — typically the most important —
- is silently lost.
- """
- client = provider._client
- provider.sync_turn("a", "b")
- provider.sync_turn("c", "d")
- provider.shutdown()
- # Both retains drained before shutdown returned.
- assert client.aretain_batch.call_count == 2
- assert provider._retain_queue.empty()
-
-
-# ---------------------------------------------------------------------------
-# on_session_switch — flush + prefetch reset behavior
-# ---------------------------------------------------------------------------
-
-
-class TestSessionSwitchBufferFlush:
- def test_buffered_turns_flushed_before_clear(self, provider_with_config):
- """retain_every_n_turns > 1 must not silently drop partial buffers
- on session switch. Whatever's in _session_turns at switch time
- should land in the OLD document under the OLD session id."""
- p = provider_with_config(retain_every_n_turns=3, retain_async=False)
- old_doc = p._document_id
-
- # Two turns buffered, no retain yet (boundary is at turn 3). The
- # writer hasn't been started either — sync_turn's early return
- # skips _ensure_writer when no retain is due.
- p.sync_turn("turn1-user", "turn1-asst")
- p.sync_turn("turn2-user", "turn2-asst")
- assert p._sync_thread is None
- p._client.aretain_batch.assert_not_called()
-
- # Switch — flush should fire under OLD document_id via the writer queue.
- p.on_session_switch("new-sid", parent_session_id="test-session", reset=True)
- p._retain_queue.join()
-
- p._client.aretain_batch.assert_called_once()
- kw = p._client.aretain_batch.call_args.kwargs
- assert kw["document_id"] == old_doc
- item = kw["items"][0]
- # Both buffered turns must be present in the flushed payload.
- content = json.loads(item["content"])
- flat = json.dumps(content)
- assert "turn1-user" in flat
- assert "turn2-user" in flat
- # Old session id must appear in lineage tags / metadata.
- assert "session:test-session" in item["tags"]
- assert item["metadata"]["session_id"] == "test-session"
-
- # And the new session must start with a clean slate.
- assert p._session_id == "new-sid"
- assert p._session_turns == []
- assert p._turn_counter == 0
- assert p._document_id != old_doc
- assert p._document_id.startswith("new-sid-")
-
-
- def test_in_flight_prefetch_thread_drained_on_switch(self, provider, monkeypatch):
- """on_session_switch must wait for an in-flight prefetch from the
- old session to settle before clearing _prefetch_result, otherwise
- the thread can race and re-populate the field after the clear."""
- import threading
-
- gate = threading.Event()
- finished = threading.Event()
-
- def _slow_prefetch():
- gate.wait(timeout=5.0)
- with provider._prefetch_lock:
- provider._prefetch_result = "old-session recall"
- finished.set()
-
- provider._prefetch_thread = threading.Thread(target=_slow_prefetch, daemon=True)
- provider._prefetch_thread.start()
-
- # Release the prefetch worker so it writes _prefetch_result, then
- # call on_session_switch — it must join the thread before clearing.
- gate.set()
- provider.on_session_switch("new-sid")
-
- assert finished.is_set(), "switch returned before prefetch thread settled"
- assert provider._prefetch_result == ""
-
- def test_flush_serializes_behind_pending_retains_via_writer_queue(
- self, provider_with_config
- ):
- """The flush closure must ride the same _retain_queue sync_turn
- uses, so it lands FIFO behind any still-queued old-session
- retains rather than racing them on a separate thread.
-
- Regression guard: an earlier draft spawned a raw threading.Thread
- for flush, overwriting _sync_thread and racing the writer against
- the same document_id.
- """
- import threading as _threading
-
- p = provider_with_config(retain_every_n_turns=2, retain_async=False)
-
- # Block the first writer job until we've enqueued the flush
- # behind it. This proves ordering — the flush MUST wait.
- gate = _threading.Event()
- call_order: list[str] = []
-
- def _aretain_batch_tracking(**kw):
- idx = kw["items"][0]["metadata"].get("turn_index", "")
- call_order.append(str(idx))
- if idx == "2":
- # First retain blocks until we've enqueued the flush.
- gate.wait(timeout=5.0)
-
- p._client.aretain_batch = AsyncMock(side_effect=_aretain_batch_tracking)
-
- # Turn 1+2 → boundary hit → retain enqueued (will block).
- p.sync_turn("turn1-user", "turn1-asst")
- p.sync_turn("turn2-user", "turn2-asst")
-
- # One more buffered turn so flush has something to land.
- p.sync_turn("turn3-user", "turn3-asst")
-
- # Switch while the first retain is still blocked on `gate`.
- p.on_session_switch("new-sid", parent_session_id="test-session")
-
- # Release the first retain. Flush must have been enqueued
- # BEHIND it, and run second.
- gate.set()
- p._retain_queue.join()
-
- # The flush carries all buffered turns; sync_turn's retain #2
- # carried the batch at boundary time. Two distinct calls.
- assert p._client.aretain_batch.call_count == 2
- # First call landed while buffer was [t1, t2]; flush landed
- # after we added t3. So the second call must be strictly after.
- assert call_order[0] == "2"
- # Flush retain has turn_index matching the buffered count at
- # switch time (3 turns accumulated, _turn_index was set to 3
- # by the last sync_turn).
- assert call_order[1] == "3"
-
-
-# ---------------------------------------------------------------------------
-# update_mode='append' capability probe + retain dispatch
-# ---------------------------------------------------------------------------
-
-
-class TestUpdateModeAppendCapability:
- def _clear_capability_cache(self):
- from plugins.memory.hindsight import _append_capability_cache, _append_capability_lock
- with _append_capability_lock:
- _append_capability_cache.clear()
-
- def test_legacy_api_falls_back_to_per_process_doc_id(self, provider, monkeypatch):
- """API returns no /version (or pre-0.5.0) — sync_turn must use the
- per-process unique doc_id and NOT pass update_mode."""
- self._clear_capability_cache()
- monkeypatch.setattr(
- "plugins.memory.hindsight._fetch_hindsight_api_version",
- lambda *a, **kw: None,
- )
- old_doc = provider._document_id
- provider.sync_turn("hello", "hi")
- provider._retain_queue.join()
-
- kw = provider._client.aretain_batch.call_args.kwargs
- assert kw["document_id"] == old_doc
- assert kw["document_id"].startswith("test-session-")
- item = kw["items"][0]
- assert "update_mode" not in item
-
- def test_modern_api_uses_stable_doc_id_with_append(self, provider, monkeypatch):
- """API on >=0.5.0 — retain uses stable session_id and sets update_mode='append'."""
- self._clear_capability_cache()
- monkeypatch.setattr(
- "plugins.memory.hindsight._fetch_hindsight_api_version",
- lambda *a, **kw: "0.5.6",
- )
- provider.sync_turn("hello", "hi")
- provider._retain_queue.join()
-
- kw = provider._client.aretain_batch.call_args.kwargs
- # Stable: just the session id, no per-process timestamp suffix.
- assert kw["document_id"] == "test-session"
- item = kw["items"][0]
- assert item["update_mode"] == "append"
-
-
- def test_session_switch_flush_picks_capability_against_old_session(
- self, provider_with_config, monkeypatch
- ):
- """When the API supports append, the flush on /reset must land
- in the OLD session's stable document, not a per-process id."""
- self._clear_capability_cache()
- monkeypatch.setattr(
- "plugins.memory.hindsight._fetch_hindsight_api_version",
- lambda *a, **kw: "0.5.6",
- )
- p = provider_with_config(retain_every_n_turns=3, retain_async=False)
- p.sync_turn("turn1-user", "turn1-asst")
- p.sync_turn("turn2-user", "turn2-asst")
- p.on_session_switch("new-sid", parent_session_id="test-session", reset=True)
- p._retain_queue.join()
-
- kw = p._client.aretain_batch.call_args.kwargs
- # Flush goes to the OLD session's stable doc, not new-sid's.
- assert kw["document_id"] == "test-session"
- assert kw["items"][0]["update_mode"] == "append"
-
-
-# ---------------------------------------------------------------------------
-# System prompt tests
-# ---------------------------------------------------------------------------
-
-
-class TestSystemPrompt:
- def test_hybrid_mode_prompt(self, provider):
- block = provider.system_prompt_block()
- assert "Hindsight Memory" in block
- assert "hindsight_recall" in block
- assert "automatically injected" in block
-
-
-# ---------------------------------------------------------------------------
-# Config schema tests
-# ---------------------------------------------------------------------------
-
-
-class TestConfigSchema:
- def test_schema_has_all_new_fields(self, provider):
- schema = provider.get_config_schema()
- keys = {f["key"] for f in schema}
- expected_keys = {
- "mode", "api_url", "api_key", "llm_provider", "llm_api_key",
- "llm_model", "bank_id", "bank_id_template", "bank_mission", "bank_retain_mission",
- "recall_budget", "memory_mode", "recall_prefetch_method",
- "retain_tags", "retain_source",
- "retain_user_prefix", "retain_assistant_prefix",
- "recall_tags", "recall_tags_match",
- "auto_recall", "auto_retain",
- "retain_every_n_turns", "retain_async", "retain_context",
- "recall_max_tokens", "recall_max_input_chars",
- "recall_prompt_preamble",
- }
- assert expected_keys.issubset(keys), f"Missing: {expected_keys - keys}"
-
-
-# ---------------------------------------------------------------------------
-# bank_id_template tests
-# ---------------------------------------------------------------------------
-
-
-class TestBankIdTemplate:
- def test_sanitize_bank_segment_passthrough(self):
- assert _sanitize_bank_segment("hermes") == "hermes"
- assert _sanitize_bank_segment("my-agent_1") == "my-agent_1"
-
-
- def test_resolve_empty_template_uses_fallback(self):
- result = _resolve_bank_id_template(
- "", fallback="hermes", profile="coder"
- )
- assert result == "hermes"
-
-
- def test_resolve_sanitizes_placeholder_values(self):
- result = _resolve_bank_id_template(
- "user-{user}", fallback="hermes",
- profile="", workspace="", platform="",
- user="[email protected]", session="",
- )
- assert result == "user-josh-example-com"
-
-
- def test_provider_uses_bank_id_template_from_config(self, tmp_path, monkeypatch):
- config = {
- "mode": "cloud",
- "apiKey": "k",
- "api_url": "http://x",
- "bank_id": "fallback-bank",
- "bank_id_template": "hermes-{profile}",
- }
- config_path = tmp_path / "hindsight" / "config.json"
- config_path.parent.mkdir(parents=True, exist_ok=True)
- config_path.write_text(json.dumps(config))
- monkeypatch.setattr("plugins.memory.hindsight.get_hermes_home", lambda: tmp_path)
-
- p = HindsightMemoryProvider()
- p.initialize(
- session_id="s1",
- hermes_home=str(tmp_path),
- platform="cli",
- agent_identity="coder",
- agent_workspace="hermes",
- )
- assert p._bank_id == "hermes-coder"
- assert p._bank_id_template == "hermes-{profile}"
-
-
-# ---------------------------------------------------------------------------
-# Availability tests
-# ---------------------------------------------------------------------------
-
-
-class TestAvailability:
- def test_available_with_api_key(self, tmp_path, monkeypatch):
- monkeypatch.setattr(
- "plugins.memory.hindsight.get_hermes_home",
- lambda: tmp_path / "nonexistent",
- )
- monkeypatch.setenv("HINDSIGHT_API_KEY", "test-key")
- p = HindsightMemoryProvider()
- assert p.is_available()
-
-
- def test_local_mode_unavailable_when_runtime_import_fails(self, tmp_path, monkeypatch):
- monkeypatch.setattr(
- "plugins.memory.hindsight.get_hermes_home",
- lambda: tmp_path / "nonexistent",
- )
- monkeypatch.setenv("HINDSIGHT_MODE", "local")
-
- def _raise(_name):
- raise RuntimeError(
- "NumPy was built with baseline optimizations: (x86_64-v2)"
- )
-
- monkeypatch.setattr(
- "importlib.import_module",
- _raise,
- )
- p = HindsightMemoryProvider()
- assert not p.is_available()
-
- def test_initialize_disables_local_mode_when_runtime_import_fails(self, tmp_path, monkeypatch):
- config = {"mode": "local_embedded"}
- config_path = tmp_path / "hindsight" / "config.json"
- config_path.parent.mkdir(parents=True, exist_ok=True)
- config_path.write_text(json.dumps(config))
- monkeypatch.setattr(
- "plugins.memory.hindsight.get_hermes_home", lambda: tmp_path
- )
-
- def _raise(_name):
- raise RuntimeError("x86_64-v2 unsupported")
-
- monkeypatch.setattr(
- "importlib.import_module",
- _raise,
- )
-
- p = HindsightMemoryProvider()
- p.initialize(session_id="test-session", hermes_home=str(tmp_path), platform="cli")
- assert p._mode == "disabled"
-
-
-class TestSharedEventLoopLifecycle:
- """Regression tests for #11923 — Hindsight leaking aiohttp ClientSession /
- TCPConnector objects in long-running gateway processes.
-
- Root cause: the module-global ``_loop`` / ``_loop_thread`` pair is shared
- across every HindsightMemoryProvider instance in the process (the plugin
- loader builds one provider per AIAgent, and the gateway builds one AIAgent
- per concurrent chat session). When a session ended, ``shutdown()`` stopped
- the shared loop, which orphaned every *other* live provider's aiohttp
- ClientSession on a dead loop. Those sessions were never closed and surfaced
- as ``Unclosed client session`` / ``Unclosed connector`` errors.
- """
-
- def test_shutdown_does_not_stop_shared_event_loop(self, provider_with_config):
- from plugins.memory import hindsight as hindsight_mod
-
- async def _noop():
- return 1
-
- # Prime the shared loop by scheduling a trivial coroutine — mirrors
- # the first time any real async call (arecall/aretain/areflect) runs.
- assert hindsight_mod._run_sync(_noop()) == 1
-
- loop_before = hindsight_mod._loop
- thread_before = hindsight_mod._loop_thread
- assert loop_before is not None and loop_before.is_running()
- assert thread_before is not None and thread_before.is_alive()
-
- # Build two independent providers (two concurrent chat sessions).
- provider_a = provider_with_config()
- provider_b = provider_with_config()
-
- # End session A.
- provider_a.shutdown()
-
- # Module-global loop/thread must still be the same live objects —
- # provider B (and any other sibling provider) is still relying on them.
- assert hindsight_mod._loop is loop_before, (
- "shutdown() swapped out the shared event loop — sibling providers "
- "would have their aiohttp ClientSession orphaned (#11923)"
- )
- assert hindsight_mod._loop.is_running(), (
- "shutdown() stopped the shared event loop — sibling providers' "
- "aiohttp sessions would leak (#11923)"
- )
- assert hindsight_mod._loop_thread is thread_before
- assert hindsight_mod._loop_thread.is_alive()
-
- # Provider B can still dispatch async work on the shared loop.
- async def _still_working():
- return 42
-
- assert hindsight_mod._run_sync(_still_working()) == 42
-
- provider_b.shutdown()
-
- @pytest.mark.parametrize("mode", ["cloud", "local_embedded"])
- def test_client_aclose_called_on_shutdown(self, provider, mode):
- """Per-provider session cleanup still runs even though the shared
- loop is preserved. Each provider's own aiohttp session is closed
- via ``self._client.aclose()``; only the (empty) shared loop survives.
- """
- assert provider._client is not None
- mock_client = provider._client
- provider._mode = mode
-
- provider.shutdown()
-
- mock_client.aclose.assert_awaited_once()
- assert provider._client is None
-
-
[email protected]("posix") # POSIX mode bits not enforced on Windows
-def test_save_config_sets_owner_only_permissions(tmp_path):
- """hindsight/config.json must be written with 0o600 so API key is not world-readable."""
- provider = HindsightMemoryProvider()
- provider.save_config({"api_key": "hd-test-key"}, str(tmp_path))
- config_file = tmp_path / "hindsight" / "config.json"
- assert config_file.exists()
- mode = stat.S_IMODE(config_file.stat().st_mode)
- assert mode == 0o600, f"Expected 0o600 (owner-only), got {oct(mode)}"
-
-
-def test_load_config_corrupt_profile_file_falls_through_to_env(tmp_path, monkeypatch):
- """A corrupt $HERMES_HOME/hindsight/config.json is not the config: the loader falls through
- (legacy file, then env) instead of returning an empty, silently-unconfigured mapping."""
- home = tmp_path / "home"
- (home / "hindsight").mkdir(parents=True)
- (home / "hindsight" / "config.json").write_text("{not json", encoding="utf-8")
- monkeypatch.setenv("HERMES_HOME", str(home))
- monkeypatch.setattr(Path, "home", lambda: tmp_path / "nohome")
- monkeypatch.setenv("HINDSIGHT_MODE", "local")
- monkeypatch.setenv("HINDSIGHT_BANK_ID", "from-env")
-
- cfg = _load_config()
-
- assert cfg["mode"] == "local"
- assert cfg["banks"]["hermes"]["bankId"] == "from-env"
-
-
-class TestLoadSimpleEnv:
- def test_bom_first_key_is_recognized(self, tmp_path):
- """A Notepad-edited .env carries a BOM; the first key must still parse
- instead of becoming '\ufeffHINDSIGHT_LLM_API_KEY'."""
- env_path = tmp_path / ".env"
- env_path.write_bytes("HINDSIGHT_LLM_API_KEY=sk-test\n".encode("utf-8"))
- values = _load_simple_env(env_path)
- assert values.get("HINDSIGHT_LLM_API_KEY") == "sk-test"
-
-
-class TestPostSetupEnvEncoding:
- def _run_cloud_post_setup(self, tmp_path, monkeypatch):
- """Drive post_setup through the cloud path with piped stdin."""
- import io
-
- monkeypatch.setattr("hermes_cli.memory_setup._curses_select",
- lambda *a, **kw: 0) # cloud mode
- monkeypatch.setattr("hermes_cli.config.save_config", lambda c: None)
- # Skip the dependency install (now routed through pm).
- import pm
- monkeypatch.setattr(pm, "sync_venv", lambda *a, **kw: None)
- # First line: API key prompt (readline). Second line: API URL (input).
- monkeypatch.setattr(sys, "stdin", io.StringIO("sk-new\n\n"))
-
- provider = HindsightMemoryProvider()
- provider.post_setup(str(tmp_path), {"memory": {}})
-
- def test_bom_first_key_updated_in_place(self, tmp_path, monkeypatch):
- """The setup writer reads the existing .env BOM-tolerantly, so a
- BOM'd first key is matched and rewritten, not duplicated."""
- env_path = tmp_path / ".env"
- env_path.write_bytes("HINDSIGHT_API_KEY=old\n".encode("utf-8"))
-
- self._run_cloud_post_setup(tmp_path, monkeypatch)
-
- content = env_path.read_text(encoding="utf-8")
- assert content.count("HINDSIGHT_API_KEY=") == 1
- assert "HINDSIGHT_API_KEY=sk-new" in content
- assert "old" not in content
- assert "" not in content
-
-
-class TestMultiplexBackgroundScope:
- """Under multiplex_profiles get_secret fails closed on an unscoped thread;
- the writer / daemon-start threads are spawned from a scoped context and
- must carry it along (#92608, #94933)."""
-
- @pytest.fixture()
- def scoped_embedded(self, tmp_path, monkeypatch):
- from agent.secret_scope import (
- build_profile_secret_scope, reset_secret_scope, set_multiplex_active, set_secret_scope,
- )
- from hermes_constants import reset_hermes_home_override, set_hermes_home_override
-
- created = []
-
- from plugins.memory.hindsight.embedded import _embedded_profile_env_path, _load_simple_env
- monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path / "user-home"))
- def start(cfg, **kwargs):
- created.append(_load_simple_env(_embedded_profile_env_path(cfg))["HINDSIGHT_API_LLM_API_KEY"])
- return "http://127.0.0.1:9158"
- monkeypatch.setattr("plugins.memory.hindsight._start_sideenv_daemon", start)
- monkeypatch.setattr("plugins.memory.hindsight._check_local_runtime", lambda: (True, ""))
- monkeypatch.setattr("plugins.memory.hindsight._ensure_client_dependency", lambda: None)
-
- home = tmp_path / "profiles" / "p1"
- (home / "hindsight").mkdir(parents=True)
- (home / ".env").write_text("HINDSIGHT_LLM_API_KEY=p1-secret\n")
- (home / "hindsight" / "config.json").write_text(json.dumps(
- {"mode": "local_embedded", "llm_provider": "openai", "llm_model": "m", "memory_mode": "hybrid"}
- ))
- # Enter the profile scope the way gateway _profile_runtime_scope does.
- set_multiplex_active(True)
- monkeypatch.setattr("plugins.memory.hindsight.get_hermes_home", lambda: home)
- home_tok = set_hermes_home_override(str(home))
- scope_tok = set_secret_scope(build_profile_secret_scope(home))
- yield created, home
- set_multiplex_active(False)
- reset_secret_scope(scope_tok)
- reset_hermes_home_override(home_tok)
-
- def test_writer_thread_resolves_profile_secret(self, scoped_embedded):
- created, home = scoped_embedded
- p = HindsightMemoryProvider()
- p._mode = "local_embedded"
- p._config = {"profile": "hermes", "llm_provider": "openai", "llm_model": "m"}
- p._ensure_writer()
- p._retain_queue.put(p._get_client) # real body: get_secret(HINDSIGHT_LLM_API_KEY)
- p._retain_queue.put(_WRITER_SENTINEL)
- p._writer_thread.join(timeout=5)
- assert created == ["p1-secret"]
-
- def test_daemon_start_thread_resolves_profile_secret(self, scoped_embedded):
- created, home = scoped_embedded
- p = HindsightMemoryProvider()
- p.initialize(session_id="s1", hermes_home=str(home), platform="cli")
- for t in threading.enumerate():
- if t.name == "hindsight-daemon-start":
- t.join(timeout=5)
- assert created == ["p1-secret"]
- p.shutdown()
-
-
-def test_append_mode_trims_retained_turns_without_dropping_any(provider, monkeypatch):
- """Append retains ship only the delta, so retained turns leave `_session_turns` (a never-ending
- session no longer pins every turn) while every turn is still shipped exactly once."""
- provider._auto_retain = True
- provider._retain_every_n_turns = 3
- monkeypatch.setattr(provider, "_ensure_writer", lambda: None)
- monkeypatch.setattr(provider, "_register_atexit", lambda: None)
- monkeypatch.setattr(provider, "_resolve_retain_target", lambda doc: ("doc", "append"))
- shipped: list[str] = []
- monkeypatch.setattr(provider, "_make_turn_retain_job",
- lambda turns, **kw: (lambda: shipped.extend(turns)))
- provider._retain_queue = MagicMock(put=lambda job: job())
-
- for i in range(7):
- provider.sync_turn(f"user {i}", f"assistant {i}")
-
- assert len(provider._session_turns) == 1 # only the un-retained tail (turn 7)
- assert provider._last_retained_turn_count == 0
- assert len(shipped) == 6 and len(set(shipped)) == 6
diff --git a/tests/plugins/memory/test_hindsight_setup_deps.py b/tests/plugins/memory/test_hindsight_setup_deps.py
deleted file mode 100644
index 83b9082b09c..00000000000
--- a/tests/plugins/memory/test_hindsight_setup_deps.py
+++ /dev/null
@@ -1,92 +0,0 @@
-"""C16: hindsight run_setup dependency install must route through pm — the
-declared ``extra: hindsight`` (uv.lock pin) for all modes — and the
-local_embedded wizard must ACTUALLY install the isolated side-env runtime via
-embedded_runtime.ensure_sideenv (hindsight-embed + hindsight-api-slim[all],
-pinned, built by PM's isolated-environment operation). Never the deleted ``tools.lazy_deps``."""
-
-from types import SimpleNamespace
-from unittest.mock import MagicMock
-
-import pytest
-
-
-def setup_mod():
- import plugins.memory.hindsight.setup as mod
- return mod
-
-
-def _fake_provider(existing=None):
- return SimpleNamespace(_config=existing or {}, save_config=MagicMock())
-
-
-def _no_network_setup(monkeypatch, setup_mod, tmp_path, mode):
- """Drive run_setup non-interactively: fixed selections, empty secrets,
- templates disabled, profile-env materialization stubbed."""
- monkeypatch.setattr(setup_mod, "_select", lambda title, items, values, current: mode)
- monkeypatch.setattr(setup_mod, "_secret_prompt", lambda label: "")
- monkeypatch.setattr(setup_mod, "_materialize_embedded_profile_env", lambda *a, **kw: None)
- import builtins
- monkeypatch.setattr(builtins, "input", lambda prompt="": "")
- import plugins.memory.hindsight.templates as templates
- monkeypatch.setattr(templates, "supported_for_mode", lambda mode: False)
- import hermes_cli.config as hermes_config
- monkeypatch.setattr(hermes_config, "save_config", lambda config: None)
- return _fake_provider(), str(tmp_path / "home"), {"memory": {}}
-
-
[email protected]("mode", ["cloud", "local_external", "local_embedded"])
-def test_setup_installs_selected_mode_and_saves(monkeypatch, setup_mod, tmp_path, capsys, mode):
- import pm
- import plugins.memory.hindsight.embedded_runtime as rt
-
- sync = MagicMock()
- side = MagicMock(return_value=rt.sideenv_root())
- monkeypatch.setattr(pm, "sync_venv", sync)
- monkeypatch.setattr(rt, "ensure_sideenv", side)
- provider, home, config = _no_network_setup(monkeypatch, setup_mod, tmp_path, mode)
- setup_mod.run_setup(provider, home, config)
- sync.assert_called_once_with(["hindsight"], explicit=True)
- assert side.call_count == (1 if mode == "local_embedded" else 0)
- assert config["memory"]["provider"] == "hindsight"
- saved = provider.save_config.call_args.args[0]
- assert saved["mode"] == mode
- assert saved["bank_id"] == "hermes"
- if mode == "local_embedded":
- out = capsys.readouterr().out
- assert "Isolated Hindsight runtime installed" in out and "not modified" in out
-
-
-class TestSyncFailureSurfaces:
- def test_sealed_refusal_warns_not_crashes(self, monkeypatch, setup_mod, tmp_path, capsys):
- import pm
-
- def refuse(extras=None, *, explicit=False):
- raise RuntimeError("venv refuses: frozen feature set")
-
- monkeypatch.setattr(pm, "sync_venv", refuse)
- provider, home, config = _no_network_setup(monkeypatch, setup_mod, tmp_path, "cloud")
-
- setup_mod.run_setup(provider, home, config)
-
- out = capsys.readouterr().out
- assert "frozen feature set" in out
- assert "hermes pm install" in out
-
-
-class TestEmbeddedInstallsIsolatedSideEnv:
- def test_embedded_install_failure_is_truthful_and_non_fatal(self, monkeypatch, setup_mod, tmp_path, capsys):
- import pm
- monkeypatch.setattr(pm, "sync_venv", lambda extras=None, *, explicit=False: None)
- import plugins.memory.hindsight.embedded_runtime as rt
- monkeypatch.setattr(rt, "ensure_sideenv",
- lambda: (_ for _ in ()).throw(RuntimeError("uv sync failed: disk full")))
- provider, home, config = _no_network_setup(monkeypatch, setup_mod, tmp_path, "local_embedded")
-
- setup_mod.run_setup(provider, home, config)
-
- out = capsys.readouterr().out
- assert "Isolated runtime install failed" in out
- assert "disk full" in out
- provider.save_config.assert_not_called()
- assert config["memory"] == {}
diff --git a/tests/plugins/memory/test_hindsight_templates.py b/tests/plugins/memory/test_hindsight_templates.py
deleted file mode 100644
index bad225080b7..00000000000
--- a/tests/plugins/memory/test_hindsight_templates.py
+++ /dev/null
@@ -1,260 +0,0 @@
-"""Tests for the Hindsight setup-wizard starter-template step."""
-
-import json
-from contextlib import contextmanager
-
-import pytest
-
-from plugins.memory.hindsight import templates as tpl
-
-
-_CATALOG = {
- "templates": [
- {"id": "conversation", "name": "Conversation", "integrations": ["litellm", "hermes"],
- "manifest_file": "templates/conversation.json"},
- {"id": "coding-agent", "name": "Coding Agent", "integrations": ["claude-code"],
- "manifest_file": "templates/coding-agent.json"},
- {"id": "hermes-gateway-bot", "name": "Gateway Bot", "integrations": ["hermes"],
- "manifest_file": "templates/hermes-gateway-bot.json"},
- ]
-}
-
-
-def test_fetch_hermes_templates_filters_to_hermes(monkeypatch):
- monkeypatch.setattr(tpl, "_get_json", lambda url: _CATALOG)
- entries = tpl.fetch_hermes_templates("https://example/templates.json")
- ids = [e["id"] for e in entries]
- assert ids == ["conversation", "hermes-gateway-bot"] # coding-agent excluded
-
-
-def test_fetch_manifest_resolves_relative_url(monkeypatch):
- seen = {}
-
- def _fake(url):
- seen["url"] = url
- return {"version": "1"}
-
- monkeypatch.setattr(tpl, "_get_json", _fake)
- tpl.fetch_manifest(
- {"manifest_file": "templates/hermes-gateway-bot.json"},
- "https://raw.example/data/templates.json",
- )
- assert seen["url"] == "https://raw.example/data/templates/hermes-gateway-bot.json"
-
-
-def test_apply_template_posts_to_import_endpoint(monkeypatch):
- captured = {}
-
- @contextmanager
- def _fake_open(req, timeout=None):
- captured["url"] = req.full_url
- captured["method"] = req.get_method()
- captured["auth"] = req.get_header("Authorization")
- captured["body"] = json.loads(req.data.decode("utf-8"))
-
- class _Resp:
- def read(self):
- return b""
-
- yield _Resp()
-
- monkeypatch.setattr(tpl, "open_credentialed_url", _fake_open)
- tpl.apply_template("https://api.hindsight.vectorize.io/", "hermes", "hsk_abc", {"version": "1"})
-
- assert captured["url"] == "https://api.hindsight.vectorize.io/v1/default/banks/hermes/import"
- assert captured["method"] == "POST"
- assert captured["auth"] == "Bearer hsk_abc"
- assert captured["body"] == {"version": "1"}
-
-
-def test_apply_template_omits_auth_when_no_key(monkeypatch):
- captured = {}
-
- @contextmanager
- def _fake_open(req, timeout=None):
- captured["auth"] = req.get_header("Authorization")
-
- class _Resp:
- def read(self):
- return b""
-
- yield _Resp()
-
- monkeypatch.setattr(tpl, "open_credentialed_url", _fake_open)
- tpl.apply_template("http://localhost:8888", "hermes", None, {"version": "1"})
- assert captured["auth"] is None
-
-
-def _select_returning(idx):
- def _select(title, items, default=0, cancel_returns=None):
- return idx
- return _select
-
-
-def _select_seq(*returns):
- it = iter(returns)
-
- def _select(title, items, default=0, cancel_returns=None):
- return next(it)
-
- return _select
-
-
-def test_supported_for_mode():
- assert tpl.supported_for_mode("cloud") is True
- assert tpl.supported_for_mode("local_external") is True
- assert tpl.supported_for_mode("local_embedded") is False
- assert tpl.supported_for_mode("local") is False
-
-
-def test_run_template_step_applies_selected(monkeypatch):
- monkeypatch.setattr(tpl, "fetch_hermes_templates", lambda url=None: [
- {"id": "hermes-gateway-bot", "name": "Gateway Bot", "manifest_file": "templates/x.json"},
- ])
- monkeypatch.setattr(tpl, "fetch_manifest", lambda entry, url=None: {"version": "1"})
- monkeypatch.setattr(tpl, "probe_existing_customization", lambda *a: False)
- applied = {}
- monkeypatch.setattr(tpl, "apply_template",
- lambda api_url, bank_id, api_key, manifest: applied.update(bank=bank_id))
-
- result = tpl.run_template_step(
- api_url="https://api", bank_id="hermes", api_key="k",
- select=_select_returning(0), cancelled=-1, log=lambda *_: None,
- )
- assert result == "hermes-gateway-bot"
- assert applied["bank"] == "hermes"
-
-
-def test_run_template_step_blank_selection_skips(monkeypatch):
- entries = [{"id": "hermes-gateway-bot", "name": "Gateway Bot", "manifest_file": "templates/x.json"}]
- monkeypatch.setattr(tpl, "fetch_hermes_templates", lambda url=None: entries)
- called = {"applied": False}
- monkeypatch.setattr(tpl, "apply_template",
- lambda *a, **k: called.update(applied=True))
- # index len(entries) == the "Blank" row
- result = tpl.run_template_step(
- api_url="https://api", bank_id="hermes", api_key="k",
- select=_select_returning(len(entries)), cancelled=-1, log=lambda *_: None,
- )
- assert result is None
- assert called["applied"] is False
-
-
-def test_run_template_step_no_templates_is_noop(monkeypatch):
- monkeypatch.setattr(tpl, "fetch_hermes_templates", lambda url=None: [])
- result = tpl.run_template_step(
- api_url="https://api", bank_id="hermes", api_key="k",
- select=_select_returning(0), cancelled=-1, log=lambda *_: None,
- )
- assert result is None
-
-
-def test_run_template_step_swallows_fetch_errors(monkeypatch):
- def _boom(url=None):
- raise RuntimeError("network down")
-
- monkeypatch.setattr(tpl, "fetch_hermes_templates", _boom)
- # must not raise
- assert tpl.run_template_step(
- api_url="https://api", bank_id="hermes", api_key="k",
- select=_select_returning(0), cancelled=-1, log=lambda *_: None,
- ) is None
-
-
-def test_run_template_step_swallows_apply_errors(monkeypatch):
- # gap 1: a failed apply (e.g. 401 for an OAuth-only user) must not crash setup.
- import urllib.error
-
- monkeypatch.setattr(tpl, "fetch_hermes_templates", lambda url=None: [
- {"id": "hermes-gateway-bot", "name": "Gateway Bot", "manifest_file": "templates/x.json"},
- ])
- monkeypatch.setattr(tpl, "fetch_manifest", lambda entry, url=None: {"version": "1"})
- monkeypatch.setattr(tpl, "probe_existing_customization", lambda *a: False)
-
- def _raise(*a, **k):
- raise urllib.error.HTTPError("u", 401, "Unauthorized", {}, None)
-
- monkeypatch.setattr(tpl, "apply_template", _raise)
- logs = []
- result = tpl.run_template_step(
- api_url="https://api", bank_id="hermes", api_key=None,
- select=_select_returning(0), cancelled=-1, log=logs.append,
- )
- assert result is None
- assert any("Could not apply" in line for line in logs)
-
-
-def _fake_open(payload):
- @contextmanager
- def _cm(req, timeout=None):
- class _Resp:
- def read(self):
- return json.dumps(payload).encode("utf-8")
-
- yield _Resp()
-
- return _cm
-
-
-def test_probe_existing_customization_true_when_bank_has_config(monkeypatch):
- monkeypatch.setattr(tpl, "open_credentialed_url",
- _fake_open({"version": "1", "bank": {"reflect_mission": "x"}}))
- assert tpl.probe_existing_customization("https://api", "hermes", "k") is True
-
-
-def test_probe_existing_customization_false_when_empty(monkeypatch):
- monkeypatch.setattr(tpl, "open_credentialed_url",
- _fake_open({"version": "1"}))
- assert tpl.probe_existing_customization("https://api", "hermes", "k") is False
-
-
-def test_probe_existing_customization_false_on_error(monkeypatch):
- def _boom(req, timeout=None):
- raise OSError("no bank")
-
- monkeypatch.setattr(tpl, "open_credentialed_url", _boom)
- assert tpl.probe_existing_customization("https://api", "missing", None) is False
-
-
-def _wire_apply(monkeypatch, customized):
- monkeypatch.setattr(tpl, "fetch_hermes_templates", lambda url=None: [
- {"id": "hermes-gateway-bot", "name": "Gateway Bot", "manifest_file": "templates/x.json"},
- ])
- monkeypatch.setattr(tpl, "fetch_manifest", lambda entry, url=None: {"version": "1"})
- monkeypatch.setattr(tpl, "probe_existing_customization", lambda *a: customized)
- called = {"applied": False}
- monkeypatch.setattr(tpl, "apply_template", lambda *a, **k: called.update(applied=True))
- return called
-
-
-def test_warns_and_keeps_existing_when_declined(monkeypatch):
- called = _wire_apply(monkeypatch, customized=True)
- # first select = pick template (0); second select = confirm -> "Keep existing" (1)
- result = tpl.run_template_step(
- api_url="https://api", bank_id="hermes", api_key="k",
- select=_select_seq(0, 1), cancelled=-1, log=lambda *_: None,
- )
- assert result is None
- assert called["applied"] is False
-
-
-def test_warns_then_applies_when_confirmed(monkeypatch):
- called = _wire_apply(monkeypatch, customized=True)
- # pick template (0), confirm "Apply" (0)
- result = tpl.run_template_step(
- api_url="https://api", bank_id="hermes", api_key="k",
- select=_select_seq(0, 0), cancelled=-1, log=lambda *_: None,
- )
- assert result == "hermes-gateway-bot"
- assert called["applied"] is True
-
-
-def test_fresh_bank_skips_the_warning(monkeypatch):
- called = _wire_apply(monkeypatch, customized=False)
- # only ONE select call (no confirm) — _select_seq with a single value proves it
- result = tpl.run_template_step(
- api_url="https://api", bank_id="hermes", api_key="k",
- select=_select_seq(0), cancelled=-1, log=lambda *_: None,
- )
- assert result == "hermes-gateway-bot"
- assert called["applied"] is True
diff --git a/tests/plugins/memory/test_multiplex_memory_identity_scope.py b/tests/plugins/memory/test_multiplex_memory_identity_scope.py
index b9a83b8350d..581a1f580e6 100644
--- a/tests/plugins/memory/test_multiplex_memory_identity_scope.py
+++ b/tests/plugins/memory/test_multiplex_memory_identity_scope.py
@@ -2,7 +2,7 @@
Under ``gateway.multiplex_profiles`` ``os.environ`` is the DEFAULT profile's ``.env``. When a secondary
profile's scope does not define MEM0_USER_ID / SUPERMEMORY_CONTAINER_TAG / RETAINDB_PROJECT /
-OPENVIKING_* / HINDSIGHT_BANK_ID / HERMES_HONCHO_HOST, the provider must fall back to its own default
+OPENVIKING_* / HERMES_HONCHO_HOST, the provider must fall back to its own default
(per-profile partition), NOT write the secondary's memories into the default profile's account.
"""
from __future__ import annotations
@@ -18,10 +18,6 @@ _DEFAULT_ENV = {
"RETAINDB_PROJECT": "proj-default", "RETAINDB_BASE_URL": "https://rdb.default",
"OPENVIKING_API_KEY": "ov-default", "OPENVIKING_ACCOUNT": "acct-default", "OPENVIKING_USER": "user-default",
"OPENVIKING_AGENT": "agent-default", "OPENVIKING_ENDPOINT": "http://ov.default",
- "HINDSIGHT_BANK_ID": "bank-default", "HINDSIGHT_MODE": "local_external", "HINDSIGHT_API_URL": "http://hs.default",
- "HINDSIGHT_RETAIN_TAGS": "tag-default", "HINDSIGHT_RETAIN_OBSERVATION_SCOPES": "per_tag",
- "HINDSIGHT_RETAIN_SOURCE": "source-default", "HINDSIGHT_RETAIN_USER_PREFIX": "UserDefault",
- "HINDSIGHT_RETAIN_ASSISTANT_PREFIX": "AssistantDefault",
"HERMES_HONCHO_HOST": "host-default", "HONCHO_BASE_URL": "https://honcho.default",
"OPENAI_API_KEY": "sk-default", "OPENAI_BASE_URL": "https://openai.default/v1",
}
@@ -49,7 +45,6 @@ def secondary_profile(monkeypatch, tmp_path):
def test_secondary_profile_memory_identity_never_inherits_default_environ(secondary_profile):
- import plugins.memory.hindsight as hindsight
import plugins.memory.mem0 as mem0
import plugins.memory.openviking as openviking
import plugins.memory.retaindb as retaindb
@@ -74,9 +69,6 @@ def test_secondary_profile_memory_identity_never_inherits_default_environ(second
client = openviking._VikingClient("http://x", "k")
assert (client._account, client._user) == ("default", "default") # the built-in tenant, not acct-default
- hcfg = hindsight._load_config()
- assert (hcfg["banks"]["hermes"]["bankId"], hcfg["mode"]) == ("hermes", "cloud")
-
assert honcho_client.resolve_active_host() != "host-default"
assert honcho_client._env_base_url() is None
@@ -97,58 +89,3 @@ def test_mem0_oss_llm_never_borrows_default_profile_openai_key(secondary_profile
secret_scope.reset_secret_scope(token)
assert llm.client.api_key == "sk-b"
assert str(llm.client.base_url).startswith("https://openai.b/v1")
-
-
-def test_hindsight_retain_shaping_is_not_re_read_from_the_default_profile_environ(secondary_profile):
- """The provider must retain with ITS OWN shaping, not the default profile's.
-
- ``_load_config`` resolves retain shaping through the secret scope, but the values it produces
- pass through ``_apply_retain_settings``, whose ``cfg_or_env`` half re-read ``os.environ`` — so
- every scoped miss came back as the default profile's tag, scope, source and speaker prefixes.
- ``metadata.source`` is opt-in by AGENTS.md, and tags are the retrieval partition, so a secondary
- profile's memories were both mislabelled and selectable by the default profile's tag filters.
- """
- import plugins.memory.hindsight as hindsight
- from plugins.memory.hindsight.settings import _DEFAULT_RETAIN_SOURCE
-
- cfg = hindsight._load_config()
- assert (cfg["retain_source"], cfg["retain_user_prefix"], cfg["retain_assistant_prefix"]) == (
- _DEFAULT_RETAIN_SOURCE, "User", "Assistant")
-
- provider = hindsight.HindsightMemoryProvider()
- provider._apply_retain_settings(cfg)
- assert provider._retain_tags == []
- assert provider._observation_scopes is None
- assert provider._retain_source == _DEFAULT_RETAIN_SOURCE
- assert (provider._retain_user_prefix, provider._retain_assistant_prefix) == ("User", "Assistant")
-
- # A config.json install never reaches ``_load_config``'s scoped read at all, so the fallback
- # inside ``_apply_retain_settings`` is the only gate for it.
- provider._apply_retain_settings({})
- assert provider._retain_tags == []
- assert provider._retain_source == _DEFAULT_RETAIN_SOURCE
-
- # The profile's OWN scoped values still win — this is isolation, not a blindfold.
- token = secret_scope.set_secret_scope({"HINDSIGHT_RETAIN_TAGS": "tag-b", "HINDSIGHT_RETAIN_SOURCE": "source-b"})
- try:
- provider._apply_retain_settings({})
- finally:
- secret_scope.reset_secret_scope(token)
- assert provider._retain_tags == ["tag-b"]
- assert provider._retain_source == "source-b"
-
-
-def test_hindsight_retain_shaping_still_reads_the_process_env_for_a_single_profile(monkeypatch, tmp_path):
- """No multiplexing: the process env IS this profile's own .env, so it must keep being read."""
- import plugins.memory.hindsight as hindsight
-
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- monkeypatch.setenv("HINDSIGHT_RETAIN_TAGS", "solo-tag")
- monkeypatch.setenv("HINDSIGHT_RETAIN_SOURCE", "solo-source")
- monkeypatch.setenv("HINDSIGHT_RETAIN_USER_PREFIX", "Operator")
-
- provider = hindsight.HindsightMemoryProvider()
- provider._apply_retain_settings({})
- assert provider._retain_tags == ["solo-tag"]
- assert provider._retain_source == "solo-source"
- assert provider._retain_user_prefix == "Operator"
diff --git a/tests/plugins/memory/test_provider_threads_inherit_profile.py b/tests/plugins/memory/test_provider_threads_inherit_profile.py
index efb127452f1..252cda49831 100644
--- a/tests/plugins/memory/test_provider_threads_inherit_profile.py
+++ b/tests/plugins/memory/test_provider_threads_inherit_profile.py
@@ -72,16 +72,6 @@ def _openviking(seen, tmp_path):
return list(workers)
-def _hindsight(seen, tmp_path):
- import plugins.memory.hindsight as hindsight
-
- p = hindsight.HindsightMemoryProvider()
- p._recall_sync, p._memory_mode, p._auto_recall, p._prefetch_waits_for_retain = False, "hybrid", True, False
- p._do_recall = lambda query: (seen.setdefault("home", get_hermes_home()) and "text", 1)
- p.queue_prefetch("remember this")
- return [p._prefetch_thread]
-
-
def _honcho(seen, tmp_path):
from plugins.memory.honcho import HonchoMemoryProvider
@@ -90,7 +80,7 @@ def _honcho(seen, tmp_path):
_PROVIDERS = {
"mem0": _mem0, "retaindb": _retaindb, "byterover": _byterover, "supermemory": _supermemory,
- "openviking": _openviking, "hindsight": _hindsight, "honcho": _honcho,
+ "openviking": _openviking, "honcho": _honcho,
}
diff --git a/tests/plugins/test_hindsight_root_guard.py b/tests/plugins/test_hindsight_root_guard.py
deleted file mode 100644
index 18db639ceac..00000000000
--- a/tests/plugins/test_hindsight_root_guard.py
+++ /dev/null
@@ -1,102 +0,0 @@
-"""Root-user guard for Hindsight local_embedded mode (issue #13125).
-
-PostgreSQL's initdb refuses to run as root, so the embedded Hindsight daemon
-can never initialize under root — without a guard it crash-restart loops
-forever, burning RAM/CPU with no user-visible error. initialize() must detect
-root up front, skip daemon startup, disable the provider, and warn the user.
-"""
-
-import importlib
-import threading
-
-import pytest
-
-hindsight = importlib.import_module("plugins.memory.hindsight")
-HindsightMemoryProvider = hindsight.HindsightMemoryProvider
-
-
-def _make_local_embedded_provider(monkeypatch):
- """Build a provider wired for local_embedded with a passing runtime probe."""
- monkeypatch.setattr(
- hindsight,
- "_load_config",
- lambda: {"mode": "local_embedded", "profile": "hermes"},
- )
- # Pretend the local runtime imports cleanly so initialize() reaches the
- # daemon-start branch instead of bailing on a missing `hindsight` package.
- monkeypatch.setattr(hindsight, "_check_local_runtime", lambda: (True, None))
- return HindsightMemoryProvider()
-
-
-def _daemon_threads_alive() -> list[str]:
- return [t.name for t in threading.enumerate() if t.name == "hindsight-daemon-start"]
-
-
-def test_local_embedded_skips_daemon_as_root(monkeypatch, caplog):
- """As root, the daemon thread must NOT start and the mode is disabled."""
- provider = _make_local_embedded_provider(monkeypatch)
- monkeypatch.setattr(hindsight.os, "geteuid", lambda: 0, raising=False)
-
- # If the guard fails, _start_daemon would call _get_client() — make that
- # explode so a regression is loud rather than silently spawning a thread.
- monkeypatch.setattr(
- provider,
- "_get_client",
- lambda: pytest.fail("daemon startup attempted while running as root"),
- )
-
- before = set(_daemon_threads_alive())
- with caplog.at_level("WARNING", logger="plugins.memory.hindsight"):
- provider.initialize(session_id="s1")
-
- assert provider._mode == "disabled"
- assert set(_daemon_threads_alive()) == before # no new daemon thread
- # The warning is surfaced to the user via the logger AND printed to
- # stderr (E2E-verified in tests/plugins/test_hindsight_root_guard.py
- # docstring rationale); capsys can't reliably capture the module-level
- # sys.stderr write under the isolation harness, so assert on the log.
- assert any("cannot run as root" in r.message for r in caplog.records)
-
-
-def _fake_thread_factory(started: threading.Event):
- """Return a Thread replacement that records start() without running work."""
- real_thread = threading.Thread
-
- def _factory(*args, **kwargs):
- if kwargs.get("name") == "hindsight-daemon-start":
- started.set()
-
- class _NoopThread:
- def start(self):
- pass
-
- return _NoopThread()
- return real_thread(*args, **kwargs)
-
- return _factory
-
-
-def test_root_warning_uses_gated_warning_callback_when_wired(monkeypatch, capsys):
- """CLI wiring passes agent._emit_warning: the notice goes through that gated sink, not raw stderr."""
- provider = _make_local_embedded_provider(monkeypatch)
- monkeypatch.setattr(hindsight.os, "geteuid", lambda: 0, raising=False)
- seen = []
- provider.initialize(session_id="s1", warning_callback=seen.append, platform="cli")
- assert provider._mode == "disabled"
- assert len(seen) == 1 and "cannot run as root" in seen[0]
- assert "cannot run as root" not in capsys.readouterr().err
-
-
[email protected]("setting", (None, False, True))
-def test_root_warning_stderr_fallback_honors_policy(tmp_path, monkeypatch, capsys, setting):
- """No warning_callback (gateway/TUI wiring): the stderr fallback follows the shared boundary;
- the logger.warning is always recorded."""
- import json
- home = tmp_path / f"home-{setting}"; home.mkdir()
- monkeypatch.setenv("HERMES_HOME", str(home))
- (home / "config.yaml").write_text(json.dumps({"display": {} if setting is None else {"suppress_warning_notifications": setting}}))
- provider = _make_local_embedded_provider(monkeypatch)
- monkeypatch.setattr(hindsight.os, "geteuid", lambda: 0, raising=False)
- provider.initialize(session_id="s1", platform="cli")
- assert provider._mode == "disabled"
- assert ("cannot run as root" in capsys.readouterr().err) is (setting is not True)
diff --git a/tests/scripts/install/test_install_clone_throttle_fallback.py b/tests/scripts/install/test_install_clone_throttle_fallback.py
index bcbb4239d68..a8d69c401ee 100644
--- a/tests/scripts/install/test_install_clone_throttle_fallback.py
+++ b/tests/scripts/install/test_install_clone_throttle_fallback.py
@@ -31,7 +31,7 @@ sleep() {{ :; }}
git() {{
if [ "$1" = clone ]; then
printf '%s\\n' "$*" >> {shlex.quote(attempts.as_posix())}
- case " $* " in *" --filter=blob:none "*) ;; *) return 1 ;; esac
+ case " $* " in *" --filter=tree:0 --no-checkout "*) ;; *) return 1 ;; esac
fi
if [ "{int(materialize_fails)}" = 1 ] && [ "${{3:-}}" = reset ]; then return 1; fi
command git "$@"
@@ -40,7 +40,7 @@ stage_repository
'''
result = subprocess.run(["bash", "-c", script], env=env, capture_output=True, text=True, timeout=30)
calls = attempts.read_text().splitlines()
- assert len([x for x in calls if "--filter=blob:none" not in x]) > 1
+ assert len(calls) > 1
assert "--no-checkout" in calls[-1]
if materialize_fails:
assert result.returncode != 0
diff --git a/tests/test_git_safety_boundary.py b/tests/test_git_safety_boundary.py
index 0d01983f050..f129b657db5 100644
--- a/tests/test_git_safety_boundary.py
+++ b/tests/test_git_safety_boundary.py
@@ -35,3 +35,22 @@ def test_guard_blocks_native_and_shell_git_mutations_without_touching_checkout(t
git(ordinary, "reset", "--hard", old)
assert git(ordinary, "rev-parse", "HEAD") == old
assert not (ordinary / "sentinel").exists()
+
+
+def test_checkout_guard_covers_write_verbs_without_blocking_queries(tmp_path):
+ from tests.git_safety import blocked_git_mutation
+
+ root = tmp_path / "checkout"
+ root.mkdir()
+ options = {"cwd": root}
+ for argv in (
+ ["commit", "-am", "change"], ["add", "-A"], ["rm", "-r", "."],
+ ["config", "url.https://example.invalid/.insteadOf", "[email protected]:"],
+ ["update-ref", "refs/heads/main", "abc"], ["branch", "-f", "main"],
+ ["worktree", "add", "../other"], ["tag", "v1"],
+ ):
+ assert blocked_git_mutation(["git", *argv], options, (root,)) == argv[0]
+ assert blocked_git_mutation(["git", *argv], {"cwd": tmp_path}, (root,)) is None
+ for argv in (["status"], ["config", "--get", "url.x.insteadOf"],
+ ["worktree", "list"], ["branch", "--show-current"], ["tag", "-l"]):
+ assert blocked_git_mutation(["git", *argv], options, (root,)) is None
diff --git a/tests/test_live_system_guard.py b/tests/test_live_system_guard.py
index ce51a08cced..33cd1f027be 100644
--- a/tests/test_live_system_guard.py
+++ b/tests/test_live_system_guard.py
@@ -7,7 +7,9 @@ All blocked-case commands use patterns that match no real process, so a
guard regression cannot kill anything.
"""
+import os
import subprocess
+import sys
import pytest
@@ -63,3 +65,16 @@ def test_gateway_start_inside_a_container_exec_is_not_blocked():
def test_gateway_start_on_the_host_is_still_blocked():
with pytest.raises(RuntimeError, match="REAL.*gateway runtime"):
subprocess.run(["python", "-m", "hermes_cli.main", "gateway", "start"])
+
+
+def test_custom_home_tmpdir_is_relocated_before_pytest_uses_it(tmp_path):
+ home = tmp_path / "custom-home"
+ scratch = home / "cache" / "scratch"
+ scratch.mkdir(parents=True)
+ env = dict(os.environ, HERMES_HOME=str(home), TMPDIR=str(scratch))
+ env.pop("HERMES_SCRATCH_DIR", None)
+ result = subprocess.run(
+ [sys.executable, "-c", "import tempfile, tests.conftest; print(tempfile.gettempdir())"],
+ env=env, capture_output=True, text=True, check=True,
+ )
+ assert not result.stdout.strip().startswith(str(home))
diff --git a/website/docs/developer-guide/middleware.md b/website/docs/developer-guide/middleware.md
index bc896049ee2..e19f05c296f 100644
--- a/website/docs/developer-guide/middleware.md
+++ b/website/docs/developer-guide/middleware.md
@@ -137,7 +137,7 @@ hermes plugins enable <plugin-name>
hermes chat --query 'Reply exactly ok'
```
-For source checkouts, use the [PM developer workflow](../../website/docs/reference/package-management.md#developer-workflow)
+For source checkouts, use the [PM developer workflow](../reference/package-management.md#developer-workflow)
and a separate development home so the runtime sees plugins and middleware from
the working tree:
diff --git a/website/docs/developer-guide/pm-audit-status.md b/website/docs/developer-guide/pm-audit-status.md
index 6be9d0a51ad..d91cc20f151 100644
--- a/website/docs/developer-guide/pm-audit-status.md
+++ b/website/docs/developer-guide/pm-audit-status.md
@@ -55,7 +55,7 @@ distinguishes runtime activation from independent test and editor environments.
| C10 | Repair uninstall dispatch and owned-link removal. |
| C13, C14 | Prepare one complete dependency environment before publication. Preserve declared constraints and explicit pins; permit compatible transitive upgrades. Infrastructure failures do not disable plugins. |
| C15, C18 | Retain recoverable tool-store entries on failed publication. Use atomic facts/config writes and context-local receipts. |
-| C16, C29 | Migrate removed dependency helpers and restore missing-dependency hints. Run the embedded Hindsight service from its separate environment. |
+| C16, C29 | Migrate removed dependency helpers and restore missing-dependency hints. |
| C20, C21 | Correct platform-test selection and make the removed-import guard inspect actual source. |
| C22, C23 | Publish immutable release artifacts before feeds and resolve FFmpeg artifacts by target. |
| C25 | Preserve paused downloads, resume handles, and single-worker ownership. |
diff --git a/website/docs/getting-started/nix-setup.md b/website/docs/getting-started/nix-setup.md
index 9ef9246ed5f..aee0a2c38f4 100644
--- a/website/docs/getting-started/nix-setup.md
+++ b/website/docs/getting-started/nix-setup.md
@@ -829,8 +829,8 @@ services.hermes-agent.extraDependencyGroups = [ "messaging" ];
```nix
# Enable a memory provider
services.hermes-agent = {
- extraDependencyGroups = [ "hindsight" ];
- settings.memory.provider = "hindsight";
+ extraDependencyGroups = [ "honcho" ];
+ settings.memory.provider = "honcho";
};
```
@@ -851,13 +851,14 @@ requirements can still fail that resolution. The table lists common groups;
| `bedrock` | AWS Bedrock (boto3) |
| `azure-identity` | Azure Entra ID auth |
| `honcho` | Honcho memory provider |
-| `hindsight` | Hindsight memory provider |
| `modal` | Modal terminal backend |
| `daytona` | Daytona terminal backend |
| `exa` | Exa web search |
| `firecrawl` | Firecrawl web search |
| `fal` | FAL image generation |
+Memory providers that live in the [plugin catalog](../user-guide/features/plugins.md) rather than in the Hermes tree (e.g. Hindsight) are not extras. Install them like any catalog plugin with `hermes plugins install hindsight`, or declaratively via [`extraPlugins`](#directory-plugins-extraplugins) pointing at the plugin's source tree.
+
Or use the pre-built `#messaging` or `#full` flake packages instead of per-extra configuration (see [Quick Start](#quick-start-any-nix-user)).
**When to use which:**
@@ -892,7 +893,7 @@ External flakes can override the package directly:
nixpkgs.overlays = [ hermes-agent.overlays.default ];
# Then:
# pkgs.hermes-agent.override { extraPythonPackages = [...]; }
- # pkgs.hermes-agent.override { extraDependencyGroups = [ "hindsight" ]; }
+ # pkgs.hermes-agent.override { extraDependencyGroups = [ "honcho" ]; }
};
}
```
@@ -1037,7 +1038,7 @@ nix build .#checks.x86_64-linux.config-roundtrip # merge script preserves use
| `extraPackages` | `listOf package` | `[]` | Extra packages available to the agent. Added to the hermes user's per-user profile so terminal commands, skills, and cron jobs all see them |
| `extraPlugins` | `listOf package` | `[]` | Directory plugin packages to symlink into `$HERMES_HOME/plugins/`. Each must contain `plugin.yaml` |
| `extraPythonPackages` | `listOf package` | `[]` | Python packages added to PYTHONPATH for entry-point plugin discovery. Use the selected package’s `python.pkgs` |
-| `extraDependencyGroups` | `listOf str` | `[]` | pyproject.toml optional extras to include in the sealed venv (e.g. `["hindsight"]`). Resolved by uv — no collisions |
+| `extraDependencyGroups` | `listOf str` | `[]` | pyproject.toml optional extras to include in the sealed venv (e.g. `["honcho"]`). Resolved by uv — no collisions |
| `restart` | `str` | `"always"` | The systemd `Restart=` policy. macOS does not use it. |
| `restartSec` | `int` | `5` | The systemd `RestartSec=` value. macOS does not use it. |
diff --git a/website/docs/integrations/index.md b/website/docs/integrations/index.md
index 67feaf70dee..adf8f6ae005 100644
--- a/website/docs/integrations/index.md
+++ b/website/docs/integrations/index.md
@@ -84,7 +84,7 @@ Speech-to-text supports eight providers: local faster-whisper (free, runs on-dev
## Memory & Personalization
- **[Built-in Memory](../user-guide/features/memory.md)** — Persistent, curated memory via `MEMORY.md` and `USER.md` files. The agent maintains bounded stores of personal notes and user profile data that survive across sessions.
-- **[Memory Providers](../user-guide/features/memory-providers.md)** — Plug in external memory backends for deeper personalization. Eight providers are supported: Honcho (dialectic reasoning), OpenViking (tiered retrieval), Mem0 (cloud extraction), Hindsight (knowledge graphs), Holographic (local SQLite), RetainDB (hybrid search), ByteRover (CLI-based), and Supermemory.
+- **[Memory Providers](../user-guide/features/memory-providers.md)** — Plug in external memory backends for deeper personalization. Seven providers ship with Hermes: Honcho (dialectic reasoning), OpenViking (tiered retrieval), Mem0 (cloud extraction), Holographic (local SQLite), RetainDB (hybrid search), ByteRover (CLI-based), and Supermemory; Hindsight (knowledge graphs) is available from the plugin catalog via `hermes plugins install hindsight`.
## Messaging Platforms
diff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.md
index 1c333ea2cc0..3b6a588811e 100644
--- a/website/docs/reference/cli-commands.md
+++ b/website/docs/reference/cli-commands.md
@@ -1559,7 +1559,7 @@ See [Hooks](../user-guide/features/hooks.md) for event signatures and payload sh
hermes memory <subcommand>
```
-Set up and manage external memory provider plugins. Available providers: honcho, openviking, mem0, hindsight, holographic, retaindb, byterover, supermemory. Only one external provider can be active at a time. Built-in memory (MEMORY.md/USER.md) is always active.
+Set up and manage external memory provider plugins. Bundled providers: honcho, openviking, mem0, holographic, retaindb, byterover, supermemory; hindsight (plugin catalog) after `hermes plugins install hindsight`. Only one external provider can be active at a time. Built-in memory (MEMORY.md/USER.md) is always active.
Subcommands:
diff --git a/website/docs/user-guide/docker.md b/website/docs/user-guide/docker.md
index f1d3da47e61..9b18f9f8949 100644
--- a/website/docs/user-guide/docker.md
+++ b/website/docs/user-guide/docker.md
@@ -523,7 +523,7 @@ The image uses Debian 13.4 and includes:
- A Python 3.14 environment synchronized from the committed `uv.lock`, followed
by a no-dependency editable install of Hermes.
- The curated extras `all`, `messaging`, `otlp`, `anthropic`, `bedrock`,
- `azure-identity`, `hindsight`, and `matrix`. This is not `--all-extras`.
+ `azure-identity`, and `matrix`. This is not `--all-extras`.
- Node.js 26 and npm from the digest-pinned Node source image.
- PM-pinned uv, Chromium, and Chromium headless shell in `/opt/hermes/tools`.
- System Git, ripgrep, FFmpeg, OpenSSH, Docker CLI, and Chromium shared libraries.
diff --git a/website/docs/user-guide/features/memory-providers.md b/website/docs/user-guide/features/memory-providers.md
index 32e18cf20ee..a2762cacd8e 100644
--- a/website/docs/user-guide/features/memory-providers.md
+++ b/website/docs/user-guide/features/memory-providers.md
@@ -6,7 +6,7 @@ description: "External memory provider plugins — Honcho, OpenViking, Mem0, Hin
# Memory Providers
-Hermes Agent ships with 8 external memory provider plugins that give the agent persistent, cross-session knowledge beyond the built-in MEMORY.md and USER.md. Only **one** external provider can be active at a time — the built-in memory is always active alongside it.
+Hermes Agent ships with 7 external memory provider plugins that give the agent persistent, cross-session knowledge beyond the built-in MEMORY.md and USER.md, and more (such as Hindsight) are available from the [plugin catalog](./plugins.md). Only **one** external provider can be active at a time — the built-in memory is always active alongside it.
## Quick Start
@@ -22,7 +22,8 @@ Or set manually in `~/.hermes/config.yaml`:
```yaml
memory:
- provider: openviking # or honcho, mem0, hindsight, holographic, retaindb, byterover, supermemory
+ provider: openviking # or honcho, mem0, holographic, retaindb, byterover, supermemory,
+ # or hindsight (plugin catalog — run `hermes plugins install hindsight` first)
```
## How It Works
@@ -434,35 +435,33 @@ The plugin authenticates with `X-API-Key` and uses the server's `/search` / `/me
### Hindsight
+:::info Plugin catalog
+Hindsight is maintained by [vectorize-io](https://github.com/vectorize-io/hindsight) and installed from the [plugin catalog](./plugins.md) rather than bundled with Hermes. Setup details live in the upstream docs: [hindsight.vectorize.io/sdks/integrations/hermes](https://hindsight.vectorize.io/sdks/integrations/hermes).
+:::
+
Long-term memory with knowledge graph, entity resolution, and multi-strategy retrieval. The `hindsight_reflect` tool provides cross-memory synthesis that no other provider offers. Automatically retains full conversation turns (including tool calls) with session-level document tracking.
| | |
|---|---|
| **Best for** | Knowledge graph-based recall with entity relationships |
-| **Requires** | Cloud: API key from [ui.hindsight.vectorize.io](https://ui.hindsight.vectorize.io). Local: LLM API key (OpenAI, Groq, OpenRouter, etc.) |
-| **Data storage** | Hindsight Cloud or local embedded PostgreSQL |
+| **Requires** | `hermes plugins install hindsight`. Cloud: API key from [ui.hindsight.vectorize.io](https://ui.hindsight.vectorize.io). Local: LLM API key (OpenAI, Groq, OpenRouter, etc.) |
+| **Data storage** | Hindsight Cloud, local embedded PostgreSQL, or an external local Hindsight server |
| **Cost** | Hindsight pricing (cloud) or free (local) |
**Tools:** `hindsight_retain` (store with entity extraction), `hindsight_recall` (multi-strategy search), `hindsight_reflect` (cross-memory synthesis)
**Setup:**
```bash
-hermes memory setup # select "hindsight"
+hermes plugins install hindsight # from the plugin catalog
+hermes memory setup # select "hindsight"
# Or manually:
hermes config set memory.provider hindsight
echo "HINDSIGHT_API_KEY=your-key" >> ~/.hermes/.env
```
-The client uses the locked `hindsight` extra through PM. Local Embedded adds
-a separately resolved runtime for `hindsight-embed` and `hindsight-api-slim`,
-outside Hermes' shared Python environment. Its generations and `active.json`
-selection live under `$HERMES_HOME/profiles/Hindsight/env/`. The daemon uses that
-interpreter, and Hermes connects through the HTTP client. Re-run
-`hermes memory setup` to install or repair the local runtime. A client dependency
-change can require restarting Hermes.
+The plugin lands in `~/.hermes/plugins/hindsight/` (per profile home) and is enabled under `plugins.enabled` in `config.yaml`. `hermes memory setup`, `hermes memory status`, `hermes plugins list` and the dashboard Memory settings all work with the catalog-installed plugin. In local embedded mode the plugin installs `hindsight-all` on first use through Hermes' lazy-install path, which honours `security.allow_lazy_installs`.
-The local Hindsight CLI belongs to the selected side environment, not the
-global PATH. Its environment is independent of the Hermes application payload.
+**Local mode UI:** `hindsight-embed -p hermes ui start`
**Config:** `$HERMES_HOME/hindsight/config.json`
@@ -482,7 +481,17 @@ global PATH. Its environment is independent of the Hermes application payload.
| `retain_assistant_prefix` | `Assistant` | Label used before assistant turns in auto-retained transcripts |
| `recall_tags` | — | Tags to filter on recall |
-See [plugin README](https://github.com/NousResearch/hermes-agent/blob/main/plugins/memory/hindsight/README.md) for the full configuration reference.
+See the [upstream Hermes integration docs](https://hindsight.vectorize.io/sdks/integrations/hermes) for the full configuration reference.
+
+#### Migrating from bundled Hindsight
+
+Hindsight used to ship inside the Hermes tree (and as the `hermes-agent[hindsight]` pip extra). If your `config.yaml` already has `memory.provider: hindsight`, there is nothing to do for most users:
+
+- `hermes update` installs the catalog plugin into every profile home that names the provider (this runs even when `security.allow_lazy_installs` is `false`).
+- If the plugin is still missing on the first agent start (`hermes chat`, the gateway, …), Hermes installs it and prints `✓ Memory provider 'hindsight' moved out of core — installed its plugin from the catalog (your memory.hindsight settings and data are unchanged).`
+- With `security.allow_lazy_installs: false`, the agent-start path instead logs one line — ``Memory provider 'hindsight' is not installed; security.allow_lazy_installs is off — run `hermes plugins install hindsight`.`` — and you run `hermes plugins install hindsight` yourself.
+
+What changes on disk: the plugin appears in `~/.hermes/plugins/hindsight/` and `config.yaml` gains `plugins.enabled: [hindsight]`. `memory.provider`, `memory.hindsight.*`, `$HERMES_HOME/hindsight/config.json`, `HINDSIGHT_API_KEY` in `.env` and your memory bank data are untouched. Verify with `hermes memory status` (provider active) and `hermes plugins list` (plugin installed and enabled).
---
@@ -702,7 +711,7 @@ package command. Restart Hermes after successful dependency preparation.
| **Honcho** | Cloud | Paid | 5 | `honcho-ai` | Dialectic user modeling + session-scoped context |
| **OpenViking** | Self-hosted | Free | 6 | `openviking` + server | Filesystem hierarchy + tiered loading |
| **Mem0** | Cloud/Self-hosted | Free/Paid | 4 | `mem0ai` | Server-side LLM extraction + self-hosted/OSS modes |
-| **Hindsight** | Cloud/Local | Free/Paid | 3 | `hindsight-client` | Knowledge graph + reflect synthesis |
+| **Hindsight** (plugin catalog) | Cloud/Local | Free/Paid | 3 | `hermes plugins install hindsight` | Knowledge graph + reflect synthesis |
| **Holographic** | Local | Free | 2 | None | HRR algebra + trust scoring |
| **RetainDB** | Cloud | $20/mo | 10 | `requests` | Delta compression |
| **ByteRover** | Local/Cloud | Free/Paid | 3 | `brv` CLI | Pre-compression extraction |
@@ -721,12 +730,13 @@ Each provider's data is isolated per [profile](../profiles.md):
## Providers Moving to the Plugin Catalog
Memory providers are moving out of the Hermes tree into their maintainers' own repositories,
-published through the [plugin catalog](./plugins.md). Nothing changes for you: the
+published through the [plugin catalog](./plugins.md) — Hindsight is the first (see
+[Migrating from bundled Hindsight](#migrating-from-bundled-hindsight)). Nothing changes for you: the
provider name, your `memory.<name>` settings, its data directory and its tools stay the same.
When a provider you have configured stops shipping with Hermes, `hermes update` installs its
catalog plugin for every profile that names it; if you update through the Desktop app, the
agent does the same the first time it starts (unless `security.allow_lazy_installs` is
-`false`, in which case it prints the `hermes plugins install <name>` one-liner instead).
+`false`, in which case it logs the `hermes plugins install <name>` one-liner instead).
## Building a Memory Provider
diff --git a/website/docs/user-guide/features/memory.md b/website/docs/user-guide/features/memory.md
index efee7737fca..afe78f83d33 100644
--- a/website/docs/user-guide/features/memory.md
+++ b/website/docs/user-guide/features/memory.md
@@ -499,7 +499,7 @@ Full details in [Gating agent skill writes](./skills.md#gating-agent-skill-write
## External Memory Providers
-For deeper, persistent memory that goes beyond MEMORY.md and USER.md, Hermes ships with 8 external memory provider plugins — including Honcho, OpenViking, Mem0, Hindsight, Holographic, RetainDB, ByteRover, and Supermemory.
+For deeper, persistent memory that goes beyond MEMORY.md and USER.md, Hermes ships with 7 external memory provider plugins — Honcho, OpenViking, Mem0, Holographic, RetainDB, ByteRover, and Supermemory — and more, such as Hindsight, are available from the [plugin catalog](plugins.md) via `hermes plugins install <name>`.
External providers run **alongside** built-in memory (never replacing it) and add capabilities like knowledge graphs, semantic search, automatic fact extraction, and cross-session user modeling.
diff --git a/website/docs/user-guide/features/overview.md b/website/docs/user-guide/features/overview.md
index c701d8ae6b2..6762f2ab8e8 100644
--- a/website/docs/user-guide/features/overview.md
+++ b/website/docs/user-guide/features/overview.md
@@ -45,7 +45,7 @@ Hermes Agent includes a rich set of capabilities that extend far beyond basic ch
- **[Fallback Providers](fallback-providers.md)** — Automatic failover to backup LLM providers when your primary model encounters errors, including independent fallback for auxiliary tasks like vision and compression.
- **[Credential Pools](credential-pools.md)** — Distribute API calls across multiple keys for the same provider. Automatic rotation on rate limits or failures.
- **[Prompt caching](../configuration#prompt-caching)** — Built-in cross-session 1-hour prefix cache for Claude on native Anthropic, OpenRouter, and Nous Portal. Always-on; no configuration required.
-- **[Memory Providers](memory-providers.md)** — Plug in external memory backends (Honcho, OpenViking, Mem0, Hindsight, Holographic, RetainDB, ByteRover, Supermemory) for cross-session user modeling and personalization beyond the built-in memory system.
+- **[Memory Providers](memory-providers.md)** — Plug in external memory backends (Honcho, OpenViking, Mem0, Holographic, RetainDB, ByteRover, Supermemory, plus Hindsight from the plugin catalog) for cross-session user modeling and personalization beyond the built-in memory system.
- **[API Server](api-server.md)** — Expose Hermes as an OpenAI-compatible HTTP endpoint. Connect any frontend that speaks the OpenAI format — Open WebUI, LobeChat, LibreChat, and more.
- **[IDE Integration (ACP)](acp.md)** — Use Hermes inside ACP-compatible editors such as VS Code, Zed, and JetBrains. Chat, tool activity, file diffs, and terminal commands render inside your editor.
- **[Batch Processing](batch-processing.md)** — Run the agent over many prompts or tasks in parallel from the CLI, with structured outputs and trajectory capture suitable for evals or downstream training pipelines.
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/nix-setup.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/nix-setup.md
index 4c5af5c9896..7eacda8fd41 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/nix-setup.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/nix-setup.md
@@ -658,16 +658,16 @@ services.hermes-agent.extraPythonPackages = [
### 可选依赖组(`extraDependencyGroups`)
-对于已在 hermes-agent 的 `pyproject.toml` 中声明的可选 extras(例如 `hindsight` 或 `honcho` 等记忆提供商),使用 `extraDependencyGroups` 在构建时将其包含到封闭的 venv 中:
+对于已在 hermes-agent 的 `pyproject.toml` 中声明的可选 extras(例如 `honcho` 等记忆提供商),使用 `extraDependencyGroups` 在构建时将其包含到封闭的 venv 中:
```nix
services.hermes-agent = {
- extraDependencyGroups = [ "hindsight" ];
- settings.memory.provider = "hindsight";
+ extraDependencyGroups = [ "honcho" ];
+ settings.memory.provider = "honcho";
};
```
-这由 uv 与核心依赖在单次解析中完成——不需要 PYTHONPATH 补丁,没有冲突风险。可用的组与 `pyproject.toml` 中 `[project.optional-dependencies]` 的键对应(例如 `"hindsight"`、`"honcho"`、`"voice"`、`"matrix"`、`"mistral"`、`"bedrock"`)。
+这由 uv 与核心依赖在单次解析中完成——不需要 PYTHONPATH 补丁,没有冲突风险。可用的组与 `pyproject.toml` 中 `[project.optional-dependencies]` 的键对应(例如 `"honcho"`、`"voice"`、`"matrix"`、`"mistral"`、`"bedrock"`)。
**何时使用哪个:**
@@ -701,7 +701,7 @@ services.hermes-agent = {
nixpkgs.overlays = [ hermes-agent.overlays.default ];
# 然后:
# pkgs.hermes-agent.override { extraPythonPackages = [...]; }
- # pkgs.hermes-agent.override { extraDependencyGroups = [ "hindsight" ]; }
+ # pkgs.hermes-agent.override { extraDependencyGroups = [ "honcho" ]; }
};
}
```
@@ -844,7 +844,7 @@ nix build .#checks.x86_64-linux.config-roundtrip # 合并脚本保留用户
| `extraPackages` | `listOf package` | `[]` | Agent 可用的额外包。添加到 hermes 用户的每用户 profile,终端命令、skills 和 cron 任务均可见 |
| `extraPlugins` | `listOf package` | `[]` | 以符号链接方式安装到 `$HERMES_HOME/plugins/` 的目录插件包。每个包必须包含 `plugin.yaml` |
| `extraPythonPackages` | `listOf package` | `[]` | 添加到 PYTHONPATH 用于入口点插件发现的 Python 包。使用所选包的 `python.pkgs` 构建 |
-| `extraDependencyGroups` | `listOf str` | `[]` | 包含到封闭 venv 中的 pyproject.toml 可选 extras(例如 `["hindsight"]`)。由 uv 解析——无冲突 |
+| `extraDependencyGroups` | `listOf str` | `[]` | 包含到封闭 venv 中的 pyproject.toml 可选 extras(例如 `["honcho"]`)。由 uv 解析——无冲突 |
| `restart` | `str` | `"always"` | systemd `Restart=` 策略 |
| `restartSec` | `int` | `5` | systemd `RestartSec=` 值 |
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/docker.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/docker.md
index df3aeec6ef8..f4255e94b16 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/docker.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/docker.md
@@ -276,7 +276,7 @@ docker run -d \
- 按提交的 `uv.lock` 同步的 Python 3.14 环境,然后无依赖地安装 Hermes 源码。
-- 选定的 extras:`all`、`messaging`、`otlp`、`anthropic`、`bedrock`、`azure-identity`、`hindsight` 和 `matrix`,不是 `--all-extras`。
+- 选定的 extras:`all`、`messaging`、`otlp`、`anthropic`、`bedrock`、`azure-identity` 和 `matrix`,不是 `--all-extras`。
- 从摘要固定的 Node 镜像提供的 Node.js 26 和 npm。
- PM 固定版本的 uv、Chromium 和 headless shell,位于 `/opt/hermes/tools`。
- 系统 Git、ripgrep、FFmpeg、OpenSSH、Docker CLI 和 Chromium 所需共享库。
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/memory-providers.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/memory-providers.md
index 44d6434df96..0f308b59f27 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/memory-providers.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/memory-providers.md
@@ -345,12 +345,9 @@ hermes config set memory.provider hindsight
echo "HINDSIGHT_API_KEY=your-key" >> ~/.hermes/.env
```
-安装向导通过 PM 的 `hindsight` extra 准备客户端。
-`local_embedded` 模式使用独立环境,选择记录位于
-`$HERMES_HOME/profiles/Hindsight/env/active.json`,不把 `hindsight-all` 安装到 Hermes 主环境。
-`local_external` 连接已有服务。各模式的平台限制仍适用。
+安装向导会自动安装依赖,并仅安装所选模式所需的内容(云端用 `hindsight-client`,本地用 `hindsight-all`)。需要 `hindsight-client >= 0.4.22`(会话启动时若版本过旧则自动升级)。
-详见[插件 README](https://github.com/NousResearch/hermes-agent/blob/main/plugins/memory/hindsight/README.md)。
+**本地模式 UI:** `hindsight-embed -p hermes ui start`
**配置:** `$HERMES_HOME/hindsight/config.json`
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/messaging/google_chat.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/messaging/google_chat.md
index 2c1da9f8755..3714e626943 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/messaging/google_chat.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/messaging/google_chat.md
@@ -144,7 +144,7 @@ GOOGLE_CHAT_MAX_BYTES=16777216 # 16 MiB — 在途消息字节
python -m plugins.platforms.google_chat.oauth --install-deps
```
-在 Docker / hosted 镜像中 `/opt/hermes/.venv` 只读。该安装程序通过 `tools.lazy_deps` 写入 `HERMES_LAZY_INSTALL_TARGET`(官方镜像为 `/opt/data/lazy-packages`),而不是 site-packages。完成后重启 gateway。发布镜像也会预装 `[google-chat]` extra,新容器不必在首次启动时再装。
+`--install-deps` 通过 PM 将 `google-chat` extra 加入受管理的 Python 环境;完成后重启 gateway。Docker / hosted 镜像中的 venv 只读,且禁用了按需安装,无法在容器内执行此步骤。发布镜像已预装 `[google-chat]` extra。
启动 gateway(网关):
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/windows-native.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/windows-native.md
index a520cc61683..0113251c901 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/windows-native.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/windows-native.md
@@ -74,7 +74,7 @@ Hermes 先下载本地描述文件,再停止自己的后端、退出并等待
PM 通过 `pm/lock.json` 管理工具版本,不使用旧的 winget/分层 pip 回退。
启动器运行工具存储中的 Python,并在导入依赖前选择完整环境。
-`hermes_cli/dep_ensure.py` 将功能需求交给 PM,不再调用 `install.ps1 -Ensure`。
+可选依赖由 PM 管理,不再调用 `install.ps1 -Ensure`。
:::tip 在 Windows 上跳过繁琐的提供商配置
在 Windows 上,逐个配置工具 API key(Firecrawl、FAL、Browser Use、OpenAI TTS)是获得可用 agent 摩擦最大的部分。[Nous Portal](./features/tool-gateway.md) 订阅通过一次 OAuth 登录即可覆盖模型**以及**所有这些工具。安装程序完成后,运行 `hermes setup --portal` 完成配置。