Skip to content

The agent that grows with you

feat(honcho): add bounded opt-in current-query recall

funky-xamarin707267095ace
diff --git a/plugins/memory/honcho/README.md b/plugins/memory/honcho/README.md
index 0c849a9a330..8439e6312a6 100644
--- a/plugins/memory/honcho/README.md
+++ b/plugins/memory/honcho/README.md
@@ -54,6 +54,28 @@ Multi-pass `.chat()` reasoning about the user, appended after base context.
Both layers are joined, then truncated to fit `contextTokens` budget via `_truncate_to_budget` (tokens × 4 chars, word-boundary safe).
+### Current-Query Recall (opt-in)
+
+Set `"recallSync": true` in `$HERMES_HOME/honcho.json` (at the root or under
+`hosts.hermes`), or enable **Current-query recall** in the memory settings or
+`hermes honcho setup`. An explicit host-level `false` overrides root-level `true`.
+
+In `context` and `hybrid` modes, due base and dialectic retrievals use the current
+user request before inference. The whole wait, including session initialization,
+optional query rewriting and dialectic passes, uses `timeout` / `requestTimeout`
+seconds, or 5 seconds when unset, zero, negative or nonfinite. The first-turn wait
+settings continue to apply only to the default asynchronous mode.
+
+Timeouts, errors, busy workers and cadence gaps omit recall instead of reusing
+another query's context. A timed-out worker keeps its slot until it exits; its
+late result is discarded. Base and dialectic retain independent cadences and
+reasoning/depth settings. `injectionFrequency: "first-turn"` suppresses only later
+base retrievals. Every dialectic pass includes the current request, including when
+rewriting is disabled or empty. Generic prewarm and post-turn automatic retrieval
+are disabled; message writes continue normally. `tools` mode is unchanged.
+
+The default is `false`, preserving background recall and cache reuse across turns.
+
### Latest-Message Query Rewrite (opt-in)
When `queryRewrite: true`, dialectic pass 0 first uses the shared
@@ -207,6 +229,7 @@ Pick **[e]** at the prompt to set the three keys directly instead of going throu
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `recallMode` | string | `"hybrid"` | `"hybrid"` (auto-inject + tools), `"context"` (auto-inject only, tools hidden), `"tools"` (tools only, no injection). Legacy `"auto"` → `"hybrid"` |
+| `recallSync` | boolean | `false` | Wait for current-query automatic recall within `timeout` / `requestTimeout` (5s when unset or invalid); omit late/busy results. Context/hybrid only |
| `observationMode` | string | `"directional"` | Preset: `"directional"` (all on) or `"unified"` (user observes self, AI observes others). Use `observation` object for granular control |
| `observation` | object | — | Per-peer observation config (see Observation section) |
diff --git a/plugins/memory/honcho/__init__.py b/plugins/memory/honcho/__init__.py
index badceff6e0c..94e30ac8c2c 100644
--- a/plugins/memory/honcho/__init__.py
+++ b/plugins/memory/honcho/__init__.py
@@ -110,6 +110,9 @@ class HonchoMemoryProvider(DialecticMixin, MemoryProvider):
self._sync_thread: Optional[threading.Thread] = None
self._memwrite_thread: Optional[threading.Thread] = None
self._recall_mode = "hybrid" # "context", "tools", or "hybrid"
+ self._recall_sync = False
+ self._recall_sync_thread: Optional[threading.Thread] = None
+ self._recall_sync_lock = threading.Lock()
# Base context cache — refreshed on context_cadence, not frozen.
self._base_context_cache: Optional[str] = None
self._base_context_lock = threading.Lock()
@@ -200,6 +203,7 @@ class HonchoMemoryProvider(DialecticMixin, MemoryProvider):
self._config = cfg
self._recall_mode = cfg.recall_mode
+ self._recall_sync = getattr(cfg, "recall_sync", False)
logger.debug("Honcho recall_mode: %s", self._recall_mode)
for name in ("injection_frequency", "context_cadence", "dialectic_cadence",
"dialectic_depth_levels", "reasoning_heuristic"):
@@ -267,19 +271,25 @@ class HonchoMemoryProvider(DialecticMixin, MemoryProvider):
self._init_auth_notice_emitted = False
return True
- def _start_session_init_background(self, *, wait_timeout: float = 0.0) -> None:
+ def _start_session_init_background(self, *, wait_timeout: float = 0.0, blocking: bool = True) -> None:
"""Start session initialization in a daemon thread so a slow/down Honcho can't
block agent construction or first prompt assembly. ``wait_timeout`` lets fast
(mock) initializations finish before returning."""
if not self._can_start_init():
return
- with self._init_lock:
- if not self._can_start_init() or (self._init_thread and self._init_thread.is_alive()):
- return
- self._init_thread = spawn_context_thread(lambda: self._run_session_init("background"), name="honcho-session-init")
- self._init_thread.start()
- if wait_timeout > 0:
- self._init_thread.join(timeout=wait_timeout)
+ if not blocking and not self._init_lock.acquire(blocking=False):
+ return
+ try:
+ with self._init_lock if blocking else contextlib.nullcontext():
+ if not self._can_start_init() or (self._init_thread and self._init_thread.is_alive()):
+ return
+ self._init_thread = spawn_context_thread(lambda: self._run_session_init("background"), name="honcho-session-init")
+ self._init_thread.start()
+ if wait_timeout > 0:
+ self._init_thread.join(timeout=wait_timeout)
+ finally:
+ if not blocking:
+ self._init_lock.release()
def _ensure_session(self) -> bool:
"""Lazily initialize the Honcho session (tools-only mode). True when the manager is ready."""
@@ -322,7 +332,7 @@ class HonchoMemoryProvider(DialecticMixin, MemoryProvider):
# Generic dialectic prewarm is incompatible with latest-message query rewriting,
# which needs the first substantive user message.
- if self._recall_mode in {"context", "hybrid"}:
+ if self._recall_mode in {"context", "hybrid"} and not self._recall_sync:
if self._query_rewriter is None or not self._query_rewrite_enabled:
self._spawn_dialectic(_PREWARM_QUERY, thread_name="honcho-prewarm-dialectic", fired_at=0,
log_label="dialectic prewarm", use_query_rewrite=False)
@@ -439,6 +449,12 @@ class HonchoMemoryProvider(DialecticMixin, MemoryProvider):
if self._cron_skipped or self._recall_mode == "tools":
return ""
+ if self._recall_sync:
+ from plugins.memory.honcho.recall_sync import prefetch_sync
+ notice = self._pop_auth_notice()
+ result = prefetch_sync(self, query)
+ return "\n\n".join(part for part in (notice, result) if part)
+
first_turn_base_deadline = (time.monotonic() + self._first_turn_wait(self._FIRST_TURN_BASE_TIMEOUT)
if self._turn_count <= 1 else None)
@@ -497,7 +513,7 @@ class HonchoMemoryProvider(DialecticMixin, MemoryProvider):
def queue_prefetch(self, query: str, *, session_id: str = "") -> None:
"""Fire background prefetch threads for the upcoming turn.
Context and dialectic refreshes have independent cadence controls."""
- if self._cron_skipped or self._recall_mode == "tools":
+ if self._cron_skipped or self._recall_mode == "tools" or self._recall_sync:
return
if not self._session_ready() or not query:
self._start_session_init_background()
diff --git a/plugins/memory/honcho/cli.py b/plugins/memory/honcho/cli.py
index fb33f12816c..eda74badd70 100644
--- a/plugins/memory/honcho/cli.py
+++ b/plugins/memory/honcho/cli.py
@@ -20,6 +20,7 @@ _INHERITED_KEYS = (
"recallMode", "writeFrequency", "sessionStrategy", "contextTokens",
"dialecticReasoningLevel", "dialecticDynamic", "dialecticMaxChars",
"messageMaxChars", "dialecticMaxInputChars", "saveMessages", "observation",
+ "recallSync",
)
# clone_honcho_for_profile also carries the operator's runtime-to-peer routing intent.
_CLONE_KEYS = _INHERITED_KEYS[:3] + ("sessionPeerPrefix",) + _INHERITED_KEYS[3:] + (
@@ -662,6 +663,10 @@ def _setup_tuning(cfg: dict, hermes_host: dict) -> None:
raw_recall = _pref(hermes_host, cfg, "recallMode", "hybrid")
_choice_step(hermes_host, "recallMode", raw_recall if raw_recall in _MODES else "hybrid", "Recall mode", _MODES)
+ hermes_host["recallSync"] = _yes(_prompt(
+ "Wait for current-query recall (bounded by request timeout, default 5s)? (y/N)",
+ default="y" if hermes_host.get("recallSync", cfg.get("recallSync", False)) else "n"))
+
current_ctx_tokens = _pref(hermes_host, cfg, "contextTokens")
_menu("Context injection per turn (hybrid/context recall modes only)",
"uncapped -- no limit (default)",
diff --git a/plugins/memory/honcho/client.py b/plugins/memory/honcho/client.py
index ba352d09c35..5d209b44ed5 100644
--- a/plugins/memory/honcho/client.py
+++ b/plugins/memory/honcho/client.py
@@ -309,6 +309,7 @@ def _behavior_fields(look: _HostLookup, explicitly_configured: bool) -> dict[str
"message_max_chars": look.parsed("messageMaxChars", int, 25000),
"dialectic_max_input_chars": look.parsed("dialecticMaxInputChars", int, 10000),
"recall_mode": _normalize_choice(look.pick("recallMode") or "hybrid", _RECALL_MODES),
+ "recall_sync": look.flag("recallSync", default=False),
"init_on_session_start": look.flag("initOnSessionStart", default=False),
"injection_frequency": look.pick("injectionFrequency", "every-turn"),
"context_cadence": look.parsed("contextCadence", int, 1),
@@ -363,6 +364,7 @@ class HonchoClientConfig:
dialectic_max_input_chars: int = 10000
# "hybrid" (context + tools) | "context" (no tools) | "tools" (no auto context)
recall_mode: str = "hybrid"
+ recall_sync: bool = False # bounded current-query automatic recall
init_on_session_start: bool = False # tools mode: init eagerly instead of on first tool call
injection_frequency: str = "every-turn" # or "first-turn"
context_cadence: int = 1 # min turns between peer.context() calls
diff --git a/plugins/memory/honcho/config_schema.py b/plugins/memory/honcho/config_schema.py
index adb1334fd5d..ebe35b6bd36 100644
--- a/plugins/memory/honcho/config_schema.py
+++ b/plugins/memory/honcho/config_schema.py
@@ -94,6 +94,9 @@ CONFIG_SCHEMA = ProviderConfigSchema(
_field("recallMode", "Recall mode", KIND_SELECT, "How memory retrieval works: hybrid, context-only, or tools-only.",
default="hybrid", info=_RECALL_MODE_INFO,
options=_opts(("hybrid", "Hybrid"), ("context", "Context only"), ("tools", "Tools only")), group="Recall"),
+ _field("recallSync", "Current-query recall", KIND_BOOL,
+ "Wait for current-query memory within the request timeout (5 seconds by default). Timeout or busy retrieval omits memory.",
+ default="false", group="Recall"),
_field("contextTokens", "Context token cap", KIND_NUMBER, "Cap on auto-injected context tokens. Blank leaves it uncapped.",
placeholder="(uncapped)", group="Recall"),
_field("initOnSessionStart", "Eager init", KIND_BOOL, "Initialize the session eagerly in tools mode instead of on first tool call.",
diff --git a/plugins/memory/honcho/recall_sync.py b/plugins/memory/honcho/recall_sync.py
new file mode 100644
index 00000000000..24bc2c9e25f
--- /dev/null
+++ b/plugins/memory/honcho/recall_sync.py
@@ -0,0 +1,113 @@
+"""Bounded current-query recall; background completion never publishes recall state."""
+
+from __future__ import annotations
+
+import logging
+import math
+import threading
+import time
+
+from plugins.memory.honcho.client import spawn_context_thread
+
+logger = logging.getLogger("plugins.memory.honcho")
+
+
+def prefetch_sync(provider, query: str) -> str:
+ timeout = provider._config.timeout if provider._config else None
+ budget = timeout if timeout is not None and math.isfinite(timeout) and timeout > 0 else 5.0
+ deadline = time.monotonic() + budget
+ if provider._is_trivial_prompt(query):
+ return ""
+ # No lock wait can extend the request budget. Keep the slot occupied even after
+ # a caller times out, until the actual worker (including any HTTP call) exits.
+ if not provider._recall_sync_lock.acquire(blocking=False):
+ return ""
+ cancelled = threading.Event()
+ try:
+ worker = provider._recall_sync_thread
+ if worker is not None and worker.is_alive():
+ return ""
+ session, turn = provider._session_key, provider._turn_count
+ if not provider._session_ready():
+ provider._start_session_init_background(blocking=False)
+ if provider._init_thread is not None:
+ provider._init_thread.join(timeout=max(0.0, deadline - time.monotonic()))
+ if not provider._session_ready():
+ return provider._pop_auth_notice()
+ manager = provider._manager
+ if session != provider._session_key or turn != provider._turn_count or time.monotonic() >= deadline:
+ return ""
+
+ context_due = (
+ not (provider._injection_frequency == "first-turn" and turn > 1)
+ and turn - provider._last_context_turn >= provider._context_cadence
+ )
+ dialectic_due = turn - provider._last_dialectic_turn >= provider._effective_cadence()
+ if not context_due and not dialectic_due:
+ return ""
+ # Resolve all mutable settings before starting the worker. The captured
+ # manager/session remain its only I/O owner, even if the provider is reused.
+ levels = [provider._resolve_pass_level(i, query=query) for i in range(provider._dialectic_depth)]
+ rewriter = provider._query_rewriter if provider._query_rewrite_enabled else None
+ holder = {}
+
+ def expired() -> bool:
+ return cancelled.is_set() or time.monotonic() >= deadline
+
+ def retrieve() -> None:
+ try:
+ if expired():
+ return
+ base = provider._format_first_turn_context(manager.get_prefetch_context(session, query) or {}) if context_due else ""
+ if expired():
+ return
+ dialectic = ""
+ if dialectic_due:
+ rewritten = ""
+ if rewriter:
+ try:
+ rewritten = rewriter(query).strip()
+ except Exception as exc:
+ logger.debug("Honcho query rewriter failed: %s", exc)
+ results = []
+ for i, level in enumerate(levels):
+ if expired():
+ return
+ if results and provider._signal_sufficient(results[-1]):
+ break
+ prompt = (provider._build_dialectic_prompt(i, results, not base) if results else
+ rewritten or "Recall evidence relevant to the user's current request.")
+ prompt = f"Current user request:\n{query}\n\n{prompt}"
+ result = manager.dialectic_query(session, prompt, reasoning_level=level,
+ peer="user", raise_errors=True)
+ if result and result.strip():
+ results.append(result)
+ dialectic = results[-1] if results else ""
+ holder["result"] = (base, dialectic)
+ except Exception as exc:
+ logger.debug("Honcho synchronous recall failed: %s", exc)
+
+ worker = spawn_context_thread(retrieve, name="honcho-recall-sync")
+ provider._recall_sync_thread = worker
+ worker.start()
+ worker.join(timeout=max(0.0, deadline - time.monotonic()))
+ if (worker.is_alive() or time.monotonic() >= deadline or "result" not in holder
+ or provider._manager is not manager or provider._session_key != session
+ or provider._turn_count != turn):
+ return ""
+ base, dialectic = holder["result"]
+ if context_due:
+ provider._last_context_turn = turn
+ if dialectic_due:
+ if dialectic:
+ provider._last_dialectic_turn = turn
+ provider._dialectic_empty_streak = 0
+ else:
+ provider._dialectic_empty_streak += 1
+ parts = [provider._pop_auth_notice(), base, dialectic]
+ return provider._truncate_to_budget("\n\n".join(part for part in parts if part and part.strip()))
+ finally:
+ # Thread.join may return before a coarse host clock crosses the deadline.
+ # Record caller abandonment explicitly before a late HTTP call can resume.
+ cancelled.set()
+ provider._recall_sync_lock.release()
diff --git a/tests/honcho_plugin/test_recall_sync.py b/tests/honcho_plugin/test_recall_sync.py
new file mode 100644
index 00000000000..77a952be412
--- /dev/null
+++ b/tests/honcho_plugin/test_recall_sync.py
@@ -0,0 +1,343 @@
+"""Current-query recall contracts through the real Honcho provider (no SDK/network)."""
+
+import json
+import threading
+import time
+from types import SimpleNamespace
+
+import pytest
+
+from plugins.memory.honcho import HonchoMemoryProvider
+from plugins.memory.honcho.client import HonchoClientConfig
+
+
+def test_recall_sync_opt_in_roundtrip_and_host_override(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ provider = HonchoMemoryProvider()
+ path = tmp_path / "honcho.json"
+ provider.save_config({"recallSync": True}, str(tmp_path))
+ assert HonchoClientConfig.from_global_config(host="hermes", config_path=path).recall_sync is True
+ provider.save_config({"hosts": {"hermes": {"recallSync": False}}}, str(tmp_path))
+ assert HonchoClientConfig.from_global_config(host="hermes", config_path=path).recall_sync is False
+ assert json.loads(path.read_text())["recallSync"] is True
+ assert HonchoClientConfig().recall_sync is False
+
+
+class RecallManager:
+ def __init__(self):
+ self.queries = []
+ self.prompts = []
+ self.queued = []
+ self.pending_context = {}
+
+ def set_context_result(self, session, context):
+ self.pending_context[session] = context
+
+ def pop_context_result(self, session):
+ return self.pending_context.pop(session, None)
+
+ def get_prefetch_context(self, session, query):
+ self.queries.append((session, query))
+ return {"representation": f"base:{query}"}
+
+ def dialectic_query(self, session, prompt, **kwargs):
+ self.prompts.append((session, prompt, kwargs))
+ return f"dialectic:{prompt}"
+
+ def prefetch_context(self, session, query):
+ self.queued.append((session, query))
+
+
+def make_provider(**options):
+ provider = HonchoMemoryProvider()
+ cfg = HonchoClientConfig(recall_sync=True, timeout=1, **options)
+ provider._config = cfg
+ provider._manager = RecallManager()
+ provider._session_key = "session-a"
+ provider._session_initialized = True
+ for name in ("recall_sync", "recall_mode", "injection_frequency", "context_cadence",
+ "dialectic_cadence", "dialectic_depth", "dialectic_depth_levels"):
+ setattr(provider, f"_{name}", getattr(cfg, name))
+ return provider
+
+
+def test_two_queries_never_consume_previous_query_caches():
+ provider = make_provider()
+ provider._base_context_cache = "STALE BASE"
+ provider._prefetch_result = "STALE DIALECTIC"
+ for turn, query in enumerate(("Plan the garden", "Debug the compiler"), 1):
+ provider.on_turn_start(turn, query)
+ result = provider.prefetch(query)
+ assert f"base:{query}" in result
+ assert "STALE" not in result
+ if turn == 2:
+ assert "Plan the garden" not in result
+ assert query in provider._manager.prompts[-1][1]
+ provider.queue_prefetch(query)
+ assert provider._manager.queries == [("session-a", "Plan the garden"), ("session-a", "Debug the compiler")]
+ assert provider._manager.queued == []
+ assert provider._base_context_cache == "STALE BASE"
+ assert provider._prefetch_result == "STALE DIALECTIC"
+ assert provider._manager.pending_context == {}
+
+
+def test_timeout_keeps_single_flight_and_late_result_cannot_publish():
+ provider = make_provider()
+ provider._config.timeout = 0.02
+ entered, release = threading.Event(), threading.Event()
+ calls = []
+
+ def blocked(session, query):
+ calls.append(query)
+ entered.set()
+ assert release.wait(3)
+ return {"representation": "LATE OLD QUERY"}
+
+ provider._manager.get_prefetch_context = blocked
+ provider._base_context_cache = "STALE"
+ provider.on_turn_start(1, "Plan the garden")
+ try:
+ started = time.monotonic()
+ assert provider.prefetch("Plan the garden") == ""
+ assert entered.wait(2)
+ worker = provider._recall_sync_thread
+ provider.on_turn_start(2, "Debug the compiler")
+ assert provider.prefetch("Debug the compiler") == ""
+ assert time.monotonic() - started < 2
+ assert provider._recall_sync_thread is worker and worker.is_alive()
+ assert calls == ["Plan the garden"]
+ assert provider._last_context_turn == provider._last_dialectic_turn == -999
+ finally:
+ release.set()
+ provider._recall_sync_thread.join(2)
+ assert provider._base_context_cache == "STALE"
+ assert provider._prefetch_result == ""
+ assert provider._manager.pending_context == {}
+ assert provider._manager.prompts == []
+ assert provider._last_context_turn == provider._last_dialectic_turn == -999
+ provider._manager.get_prefetch_context = lambda session, query: {"card": query}
+ assert "Debug the compiler" in provider.prefetch("Debug the compiler")
+
+
+def test_cadences_are_independent_and_gaps_do_not_reuse_context():
+ provider = make_provider(context_cadence=3, dialectic_cadence=2)
+ results = []
+ for turn in range(1, 5):
+ query = f"Discuss project number {turn}"
+ provider.on_turn_start(turn, query)
+ results.append(provider.prefetch(query))
+ assert results[1] == ""
+ assert "base:" not in results[2] and "dialectic:" in results[2]
+ assert "base:" in results[3] and "dialectic:" not in results[3]
+ assert provider._last_context_turn == 4 and provider._last_dialectic_turn == 3
+
+
+def test_first_turn_base_preserves_query_specific_dialectic_depth():
+ provider = make_provider(injection_frequency="first-turn", dialectic_depth=3,
+ dialectic_depth_levels=["minimal", "medium", "high"])
+ provider._query_rewrite_enabled = True
+ provider._query_rewriter = lambda query: ""
+ provider._manager.dialectic_query = lambda session, prompt, **kw: (
+ provider._manager.prompts.append((session, prompt, kw)) or "short evidence")
+ provider.on_turn_start(2, "Debug the compiler")
+ result = provider.prefetch("Debug the compiler")
+ assert result == "short evidence"
+ assert provider._manager.queries == []
+ assert [entry[2]["reasoning_level"] for entry in provider._manager.prompts] == ["minimal", "medium", "high"]
+ assert all("Debug the compiler" in entry[1] for entry in provider._manager.prompts)
+
+
[email protected]("changed", ["manager", "session", "turn"])
+def test_owner_change_discards_result_and_bookkeeping(changed):
+ provider = make_provider()
+ provider.on_turn_start(1, "Plan the garden")
+
+ def changed_owner(session, query):
+ if changed == "manager":
+ provider._manager = RecallManager()
+ elif changed == "session":
+ provider._session_key = "session-b"
+ else:
+ provider.on_turn_start(2, "Debug the compiler")
+ return {"card": "old owner"}
+
+ provider._manager.get_prefetch_context = changed_owner
+ assert provider.prefetch("Plan the garden") == ""
+ assert provider._last_context_turn == provider._last_dialectic_turn == -999
+
+
+def test_exception_and_trivial_prompt_do_not_reuse_cache():
+ provider = make_provider()
+ provider._base_context_cache = "STALE"
+ provider._prefetch_result = "STALE"
+ def fail(*args):
+ raise RuntimeError("offline")
+ provider._manager.get_prefetch_context = fail
+ assert provider.prefetch("Debug the compiler") == ""
+ assert provider.prefetch("thanks") == ""
+ assert provider._last_context_turn == provider._last_dialectic_turn == -999
+
+
+def test_default_queue_and_tools_mode_unchanged():
+ provider = make_provider()
+ provider._recall_sync = False
+ provider._config.recall_sync = False
+ provider._last_dialectic_turn = 1
+ provider.on_turn_start(1, "Plan the garden")
+ provider._base_context_cache = "legacy cached context"
+ provider._prefetch_result = "legacy pending dialectic"
+ assert provider.prefetch("Plan the garden") == "legacy cached context\n\nlegacy pending dialectic"
+ provider.queue_prefetch("Plan the garden")
+ assert provider._manager.queued == [("session-a", "Plan the garden")]
+ provider._recall_sync = True
+ provider._recall_mode = "tools"
+ assert provider.prefetch("Debug the compiler") == ""
+ assert provider._manager.queries == []
+
+
[email protected]("timeout", [None, 0, -1, float("inf"), float("nan")])
+def test_invalid_timeout_has_finite_default(timeout, monkeypatch):
+ provider = make_provider()
+ provider._config.timeout = timeout
+ waits = []
+ monkeypatch.setattr(threading.Thread, "join", lambda self, timeout=None: waits.append(timeout))
+ provider.prefetch("Debug the compiler")
+ assert waits and all(0 <= wait <= 5 for wait in waits)
+
+
+def test_setup_preserves_explicit_host_opt_out(monkeypatch):
+ from plugins.memory.honcho import cli
+ monkeypatch.setattr(cli, "_prompt", lambda label, default=None, **kw: default or "")
+ host = {"recallSync": False}
+ cli._setup_tuning({"recallSync": True}, host)
+ assert host["recallSync"] is False
+
+
+def test_runtime_auth_notice_survives_failed_sync_recall():
+ provider = make_provider()
+ notices = ["authorization revoked"]
+ provider._manager.pop_auth_notice = lambda: notices.pop() if notices else None
+ def fail(*args, **kwargs):
+ raise RuntimeError("authorization revoked")
+ provider._manager.dialectic_query = fail
+ result = provider.prefetch("Debug the compiler")
+ assert "[Honcho memory status]" in result
+ assert "authorization revoked" in result
+ assert provider.prefetch("Plan the garden") == ""
+
+
+def test_setup_and_initialize_propagate_flag_without_prewarm(tmp_path, monkeypatch):
+ from plugins.memory.honcho import cli, client, session
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setattr(cli, "_prompt", lambda label, default=None, **kw:
+ "y" if label.startswith("Wait for current-query") else default or "")
+ host = {}
+ cli._setup_tuning({}, host)
+ assert host["recallSync"] is True
+ provider = HonchoMemoryProvider()
+ provider.save_config({"baseUrl": "http://example.invalid", "hosts": {"hermes": host}}, str(tmp_path))
+ cfg = HonchoClientConfig.from_global_config(host="hermes", config_path=tmp_path / "honcho.json")
+ monkeypatch.setattr(client.HonchoClientConfig, "from_global_config", lambda: cfg)
+ monkeypatch.setattr(client, "get_honcho_client", lambda cfg: object())
+ messages, saved = [], []
+ record = SimpleNamespace(messages=["existing"], add_message=lambda role, content: messages.append((role, content)))
+ manager = RecallManager()
+ manager.get_or_create = lambda key: record
+ manager.save = lambda value: saved.append(value)
+ monkeypatch.setattr(session, "HonchoSessionManager", lambda **kw: manager)
+ provider.initialize("session-a")
+ provider._init_thread.join(2)
+ assert provider._session_initialized and provider._recall_sync
+ assert provider._prefetch_thread is None and manager.prompts == []
+ provider.sync_turn("Plan the garden", "Start with soil")
+ provider._sync_thread.join(2)
+ assert messages == [("user", "Plan the garden"), ("assistant", "Start with soil")]
+ assert saved == [record]
+
+
+def test_session_context_mixin_forwards_each_query_through_controlled_http():
+ """Real read mixin with a controlled HTTP seam, not an SDK/hosted E2E."""
+ import httpx
+ from plugins.memory.honcho.session_context import SessionContextMixin
+ requests = []
+ def respond(request):
+ requests.append(request)
+ query = request.url.params.get("search_query", "identity")
+ return httpx.Response(200, json={"representation": query, "peer_card": ["fact"]})
+ with httpx.Client(transport=httpx.MockTransport(respond)) as http:
+ class Peer:
+ def context(self, **kwargs):
+ return SimpleNamespace(**http.get("https://honcho.invalid/context", params=kwargs).json())
+
+ manager = SessionContextMixin()
+ manager._cache = {"session-a": SimpleNamespace(honcho_session_id="id", user_peer_id="user", assistant_peer_id="ai")}
+ manager._sessions_cache = {}
+ manager._authed_call = lambda label, fn: fn()
+ manager._get_or_create_peer = lambda peer: Peer()
+ manager._resolve_observer_target = lambda session, peer: ("ai", "user")
+ provider = make_provider(dialectic_cadence=10)
+ provider._manager = manager
+ provider._last_dialectic_turn = 0
+ for turn, query in enumerate(("Plan the garden", "Debug the compiler"), 1):
+ provider.on_turn_start(turn, query)
+ assert query in provider.prefetch(query)
+ assert [r.url.params["search_query"] for r in requests if "search_query" in r.url.params] == [
+ "Plan the garden", "Debug the compiler"]
+
+
+def test_initialization_wait_and_lock_contention_stay_bounded():
+ provider = make_provider()
+ provider._config.timeout = 0.02
+ provider._session_initialized = False
+ provider._manager = None
+ provider._lazy_init_kwargs = {}
+ release = threading.Event()
+ provider._init_thread = threading.Thread(target=lambda: release.wait(3), daemon=True)
+ provider._init_thread.start()
+ provider._init_lock.acquire()
+ try:
+ started = time.monotonic()
+ assert provider.prefetch("Debug the compiler") == ""
+ assert time.monotonic() - started < 2
+ assert provider._recall_sync_thread is None
+ finally:
+ provider._init_lock.release()
+ release.set()
+ provider._init_thread.join(2)
+
+
[email protected]("phase", ["rewrite", "dialectic"])
+def test_slow_dialectic_pipeline_has_one_deadline_and_no_late_bookkeeping(phase):
+ provider = make_provider()
+ provider._config.timeout = 0.02
+ provider._query_rewrite_enabled = True
+ release = threading.Event()
+ def blocked(*args, **kwargs):
+ assert release.wait(3)
+ return "late result"
+ if phase == "rewrite":
+ provider._query_rewriter = blocked
+ else:
+ provider._manager.dialectic_query = blocked
+ try:
+ started = time.monotonic()
+ assert provider.prefetch("Debug the compiler") == ""
+ assert time.monotonic() - started < 2
+ finally:
+ release.set()
+ provider._recall_sync_thread.join(2)
+ assert provider._last_context_turn == provider._last_dialectic_turn == -999
+ assert provider._base_context_cache is None and provider._prefetch_result == ""
+ assert provider._manager.pending_context == {}
+ if phase == "rewrite":
+ assert provider._manager.prompts == []
+
+
+def test_dialectic_exception_discards_partial_base_without_advancing():
+ provider = make_provider()
+ def fail(session, prompt, **kwargs):
+ assert kwargs["raise_errors"] is True
+ raise RuntimeError("dialectic unavailable")
+ provider._manager.dialectic_query = fail
+ assert provider.prefetch("Debug the compiler") == ""
+ assert provider._last_context_turn == provider._last_dialectic_turn == -999