Skip to content

The agent that grows with you

fix(memory): make external prefetch spilling opt-in

Erosika2327290b0df3
diff --git a/agent/memory_manager.py b/agent/memory_manager.py
index 3c001deb77a..63c75957db0 100644
--- a/agent/memory_manager.py
+++ b/agent/memory_manager.py
@@ -449,8 +449,18 @@ class MemoryManager:
schemas = list(provider.get_tool_schemas())
if provider.name != "builtin":
+ from hermes_cli.config import load_config
+
+ # Recall is provider-ranked: keep it whole unless this profile opts in.
+ # Snapshot both gates at registration, never re-read them mid-conversation.
+ memory = load_config().get("memory", {})
+ spill_config = get_spill_config()
+ spill_config["enabled"] = (
+ spill_config["enabled"] and isinstance(memory, dict)
+ and memory.get("prefetch_spill_enabled", False) is True
+ )
+ self._external_prefetch_spill_config = spill_config
self._has_external = True
- self._external_prefetch_spill_config = get_spill_config()
self._providers.append(provider)
@@ -548,8 +558,8 @@ class MemoryManager:
raise result_box["error"]
result = result_box.get("value", "")
if result and result.strip():
- # Prefetch is stamped into the user turn's api_content and replayed every later turn;
- # spill oversized results like plugin hook output so one provider can't inflate the prefix.
+ # Opt-in spill limits recall replayed with the user turn's api_content;
+ # the registration snapshot leaves provider-ranked results intact by default.
result = spill_if_oversized(
result, session_id=session_id, source=f"{provider.name} memory prefetch",
config=self._external_prefetch_spill_config,
diff --git a/cli-config.yaml.example b/cli-config.yaml.example
index 46f4272b68b..629ea2ea937 100644
--- a/cli-config.yaml.example
+++ b/cli-config.yaml.example
@@ -997,6 +997,10 @@ memory:
# User profile: preferences, communication style, expectations
user_profile_enabled: true
+
+ # External prefetch only: opt in to head/tail previews using hooks.output_spill.
+ # Defaults to keeping the full provider-ranked recall. Restart to apply changes.
+ prefetch_spill_enabled: false
# Character limits (~2.75 chars per token, model-independent)
memory_char_limit: 2200 # ~800 tokens
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index afa89f42ae6..12ff5157405 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -1311,6 +1311,7 @@ DEFAULT_CONFIG = {
"memory": { # Persistent memory — bounded curated memory injected into the system prompt
"memory_enabled": True,
"user_profile_enabled": True,
+ "prefetch_spill_enabled": False, # External recall opt-in to hooks.output_spill.
# Approval gate for memory writes on BOTH foreground turns and the background review fork.
# true = foreground writes prompt inline; background writes are staged (/memory
# pending|approve <id>|reject <id>). To disable memory: memory_enabled.
@@ -1319,9 +1320,8 @@ DEFAULT_CONFIG = {
"user_char_limit": 1375, # ~500 tokens at 2.75 chars/token
# 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: "holographic",
- # "retaindb", "byterover", or a catalog-installed one ("honcho", "hindsight", "supermemory",
- # "mem0", "openviking").
+ # One external provider: bundled (holographic, retaindb, byterover) or catalog-installed
+ # (honcho, hindsight, supermemory, mem0, openviking). Empty = built-in only.
"provider": "",
},
# Subagent delegation — override the provider:model used by delegate_task so children run on a
diff --git a/tests/agent/test_memory_provider.py b/tests/agent/test_memory_provider.py
index 4b3c0df6c2a..68d41482eb2 100644
--- a/tests/agent/test_memory_provider.py
+++ b/tests/agent/test_memory_provider.py
@@ -172,11 +172,16 @@ class TestMemoryManager:
@staticmethod
def _set_spill_config(monkeypatch, tmp_path, *, max_chars):
- monkeypatch.setattr(
- "agent.memory_manager.get_spill_config",
- lambda: {"enabled": True, "max_chars": max_chars, "preview_head": 12,
- "preview_tail": 12, "directory": str(tmp_path)},
- )
+ from hermes_cli.config import atomic_config_write
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ atomic_config_write(tmp_path / "config.yaml", {
+ "memory": {"prefetch_spill_enabled": True},
+ "hooks": {"output_spill": {
+ "enabled": True, "max_chars": max_chars, "preview_head": 12,
+ "preview_tail": 12, "directory": str(tmp_path),
+ }},
+ })
def test_oversized_external_prefetch_is_spilled(self, tmp_path, monkeypatch):
self._set_spill_config(monkeypatch, tmp_path, max_chars=40)
@@ -202,6 +207,121 @@ class TestMemoryManager:
assert mgr.prefetch_all("what do you remember?", session_id="s") == provider._prefetch_result
assert not list(tmp_path.rglob("*.txt"))
+ @pytest.mark.parametrize("memory, hooks_enabled", [
+ ({}, True),
+ ({"prefetch_spill_enabled": False}, True),
+ ({"prefetch_spill_enabled": True}, False),
+ ])
+ def test_prefetch_spill_requires_opt_in_without_changing_hooks(
+ self, tmp_path, monkeypatch, memory, hooks_enabled,
+ ):
+ """Provider-ranked recall stays intact unless both spill switches permit it (#130974)."""
+ from agent.turn_context import _collect_pre_llm_call_context
+ from hermes_cli.config import atomic_config_write
+ from tools.hook_output_spill import DEFAULT_MAX_CHARS
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ atomic_config_write(tmp_path / "config.yaml", {
+ "memory": memory,
+ "hooks": {"output_spill": {} if hooks_enabled else {"enabled": False}},
+ })
+ text = "start\n" + "ranked middle\n" * DEFAULT_MAX_CHARS + "end\n"
+ provider = FakeMemoryProvider("external")
+ provider._prefetch_result = text
+ mgr = MemoryManager()
+ mgr.add_provider(provider)
+
+ assert mgr.prefetch_all("recall", session_id="memory") == text
+ assert not (tmp_path / "hook_outputs").exists()
+
+ # Exercise the independent plugin-hook consumer, not just the spill helper.
+ monkeypatch.setattr("hermes_cli.lifecycle.invoke_hook", lambda *a, **kw: [{"context": text}])
+ result = _collect_pre_llm_call_context(
+ SimpleNamespace(session_id="hook", model="test"), effective_task_id="task",
+ turn_id="turn", original_user_message="recall", messages=[], conversation_history=[],
+ )
+ if hooks_enabled:
+ (saved,) = (tmp_path / "hook_outputs" / "hook").glob("*.txt")
+ assert saved.read_text(encoding="utf-8") == text
+ assert str(saved) in result and "plugin hook output truncated" in result
+ else:
+ assert result == text
+ assert not (tmp_path / "hook_outputs").exists()
+
+ atomic_config_write(tmp_path / "config.yaml", {
+ "memory": {"prefetch_spill_enabled": True},
+ "hooks": {"output_spill": {"enabled": True}},
+ })
+ assert mgr.prefetch_all("recall again", session_id="memory") == text
+ assert not (tmp_path / "hook_outputs" / "memory").exists()
+
+ def test_prefetch_spill_profile_snapshot_preserves_opt_in(self, tmp_path, monkeypatch):
+ """A→B→A config reads are isolated; existing managers keep their registration policy."""
+ from agent.secret_scope import (
+ is_multiplex_active, reset_secret_scope, set_multiplex_active, set_secret_scope,
+ )
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+ from hermes_cli.config import atomic_config_write
+
+ a, b = tmp_path / "a", tmp_path / "b"
+ a.mkdir()
+ b.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(a)) # Ambient launch home never follows B.
+ monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
+ shared = {"max_chars": 40, "preview_head": 12, "preview_tail": 7,
+ "directory": str(a / "recall")}
+ atomic_config_write(a / "config.yaml", {
+ "memory": {"prefetch_spill_enabled": True}, "hooks": {"output_spill": shared},
+ })
+ atomic_config_write(b / "config.yaml", {"memory": {"prefetch_spill_enabled": False}})
+ text = "HEAD-CONTEXT\n" + "ranked middle\n" * 2000 + "TAIL!!\n"
+ managers = {}
+ was_multiplex = is_multiplex_active()
+ set_multiplex_active(True)
+ try:
+ for home in (a, b, a):
+ home_token = set_hermes_home_override(home)
+ secret_token = set_secret_scope({}, profile_home=str(home))
+ try:
+ if home not in managers:
+ provider = FakeMemoryProvider("external")
+ provider._prefetch_result = text
+ mgr = MemoryManager()
+ mgr.add_provider(provider)
+ managers[home] = mgr
+ mgr = managers[home]
+ if home == b:
+ assert mgr.prefetch_all("recall", session_id="s") == text
+ assert not (b / "hook_outputs").exists()
+ continue
+ result = mgr.prefetch_all("recall", session_id="s")
+ saved = list((a / "recall" / "s").glob("*.txt"))
+ assert saved and all(p.read_text(encoding="utf-8") == text for p in saved)
+ assert any(str(p) in result for p in saved)
+ assert result.endswith(f"--- head ---\n{text[:12]}\n--- tail ---\n{text[-7:]}")
+ assert "ranked middle" not in result
+ # Subsequent config edits apply only to newly registered providers.
+ atomic_config_write(a / "config.yaml", {
+ "memory": {"prefetch_spill_enabled": False},
+ "hooks": {"output_spill": {**shared, "enabled": False}},
+ })
+ finally:
+ reset_secret_scope(secret_token)
+ reset_hermes_home_override(home_token)
+ home_token = set_hermes_home_override(a)
+ secret_token = set_secret_scope({}, profile_home=str(a))
+ try:
+ fresh = MemoryManager()
+ fresh.add_provider(provider := FakeMemoryProvider("external"))
+ provider._prefetch_result = text
+ assert fresh.prefetch_all("recall", session_id="fresh") == text
+ assert not (a / "recall" / "fresh").exists()
+ finally:
+ reset_secret_scope(secret_token)
+ reset_hermes_home_override(home_token)
+ finally:
+ set_multiplex_active(was_multiplex)
+
def test_prefetch_merges_results(self):
mgr = MemoryManager()
p1 = FakeMemoryProvider("builtin")
diff --git a/website/docs/developer-guide/memory-provider-plugin.md b/website/docs/developer-guide/memory-provider-plugin.md
index d1a921f0816..bcd83c8fbe2 100644
--- a/website/docs/developer-guide/memory-provider-plugin.md
+++ b/website/docs/developer-guide/memory-provider-plugin.md
@@ -188,13 +188,27 @@ identity should skip destructive mirroring when it is absent.
### Oversized prefetch results
-External `prefetch()` results above the configured spill threshold are written
-to a private spill file and replaced with the configured head/tail preview.
-The preview includes the path so the agent can read the full result when it is
-actually needed. Results at or below the threshold are returned unchanged.
+External `prefetch()` results are returned in full by default, preserving the
+provider's relevance-ranked recall. To opt into spilling oversized results for
+the active profile, set:
-This uses the shared `hooks.output_spill` settings (`10,000` characters by
-default); see [Plugins — oversized-context spill](./plugins/index.md#oversized-context-spill).
+```yaml
+memory:
+ prefetch_spill_enabled: true # default: false
+```
+
+When enabled, results above the shared `hooks.output_spill.max_chars` threshold
+(default `10,000` characters) are written to a private spill file and replaced
+with the configured head/tail preview plus its path. The default preview keeps
+only the first and last `500` characters; the model must read the file to recover
+the middle. Results at or below the threshold remain unchanged.
+
+The shared `hooks.output_spill` preview lengths and directory still apply, and
+`hooks.output_spill.enabled: false` disables spilling even with memory opt-in.
+Both settings are snapshotted when the external provider is registered; restart
+Hermes to apply changes to existing sessions. Built-in memory and normal
+plugin-hook spilling are unaffected. See
+[Plugins — oversized-context spill](./plugins/index.md#oversized-context-spill).
## Pre-Compress Checkpoints (fail-closed)
diff --git a/website/docs/user-guide/features/memory.md b/website/docs/user-guide/features/memory.md
index 3b953e17424..1926e491cce 100644
--- a/website/docs/user-guide/features/memory.md
+++ b/website/docs/user-guide/features/memory.md
@@ -272,6 +272,7 @@ memory:
memory_char_limit: 2200 # ~800 tokens
user_char_limit: 1375 # ~500 tokens
write_approval: false # false = write freely (default) | true = require approval
+ prefetch_spill_enabled: false # external recall stays intact unless explicitly enabled
```
Setting **both** `memory_enabled` and `user_profile_enabled` to `false` turns the
@@ -289,6 +290,21 @@ guidance for a narrower profile-only block. The tool schema advertises only the
`user` target, and direct or staged writes to disabled `MEMORY.md` are rejected.
The inverse configuration advertises only `memory` and rejects `USER.md` writes.
+### External recall size
+
+External memory providers return their full prefetched context by default.
+`memory.prefetch_spill_enabled: true` opts the active profile into replacing
+oversized recall with a head/tail preview and a file path. This can reduce
+replayed context, but the relevance-ranked middle is no longer immediately
+visible to the model. Prefer your provider's own recall budget when available.
+
+The opt-in uses the shared `hooks.output_spill` threshold, preview lengths, and
+directory; `hooks.output_spill.enabled: false` still disables it. Normal plugin
+hooks continue to spill by default, independently of the memory opt-in. Settings
+are captured at provider registration: restart Hermes after changing them.
+See [oversized prefetch results](../../developer-guide/memory-provider-plugin.md#oversized-prefetch-results)
+for the configuration details.
+
## Controlling memory writes (`write_approval`)
By default the agent saves memory freely — including from the background