The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(honcho): keep observation flags across a flush rebuild, never orphan an evicted session, namespace dashboard logins
Erosikabeab8b6f2776
diff --git a/plugins/memory/honcho/README.md b/plugins/memory/honcho/README.mdindex e8cdb836f64..57c7fd21644 100644--- a/plugins/memory/honcho/README.md+++ b/plugins/memory/honcho/README.md@@ -203,6 +203,8 @@ In gateway deployments (Telegram, Discord, Slack, etc.) each user arrives with a| `userPeerAliases` | object | `{}` | Map of runtime IDs to peer IDs (`{"7654321": "alice"}`). Many-to-one is the intended pattern — alias all your runtime IDs to one peer name. One-to-many is not supported; one runtime ID resolves to exactly one peer || `runtimePeerPrefix` | string | `""` | Prepended to unknown runtime IDs to namespace them (e.g. `"telegram_"` → `telegram_7654321`). Used only when no alias matches. Prevents collisions between platforms whose runtime IDs share the same shape |+A dashboard login is a runtime identity too. The desktop passes `<provider>:<user id>` (for example `basic:alice` or `oidc:google-oauth2|1183…`) as the runtime user, so a logged-in session resolves like a gateway user: alias, then prefix, else the raw id. Enabling dashboard login on an install that ran on `peerName` moves new sessions to that peer. Keep the old history with `pinUserPeer: true` or a `userPeerAliases` entry for the login id. Without a login the desktop still uses `peerName`.+> **Deprecated:** `pinPeerName` is a legacy alias for `pinUserPeer`, still read for back-compat (`pinUserPeer` wins where both are set). `hermes honcho setup` migrates it onto `pinUserPeer` on touch and never writes it.**Resolver ladder** (first match wins):@@ -342,6 +344,8 @@ Host key is derived from the active Hermes profile: `hermes` (default) or `herme| `contextCadence` | int | `1` | Minimum turns between base context refreshes (session summary + representation + card) || `dialecticCadence` | int | `1` | Minimum turns between dialectic `.chat()` firings || `injectionFrequency` | string | `"every-turn"` | `"every-turn"` or `"first-turn"` (inject base context on the first user message only; the dialectic supplement keeps its own cadence) |+| `injection.sessionStart` | list | unset | Which base-context sections to inject: any of `summary`, `peerRepresentation`, `peerCard`, `aiRepresentation`, `aiCard`. Unset injects all of them in that order. `[]` injects nothing. A host block with an `injection` object replaces the root pin wholesale |+| `logging` | bool | `false` | Append one JSON record per turn to `~/.honcho/injection.log` saying what was injected and why. The file is owner-only and holds the user's representation verbatim. `HONCHO_LOGGING=1` also switches it on and `HONCHO_INJECTION_LOG=<path>` moves it || `queryRewrite` | bool | `false` | Rewrite the latest message into a retrieval query before dialectic (one extra auxiliary LLM call per cycle) || `firstTurnBaseWait` | float | `3.0` | Max seconds turn 1 waits for base context / session init. `0` disables the wait (fully async; context surfaces on later turns). Turns 2+ never wait on a stalled init || `firstTurnDialecticWait` | float | `2.0` | Max seconds turn 1 waits for a dialectic result. `0` disables |diff --git a/plugins/memory/honcho/__init__.py b/plugins/memory/honcho/__init__.pyindex 9f1e69bd434..a37b1f8064a 100644--- a/plugins/memory/honcho/__init__.py+++ b/plugins/memory/honcho/__init__.py@@ -83,7 +83,25 @@ _PROMPT_HEADERS = {),}-# (context key, section header) for the injected base-context block, in display order.+_LOCAL_PLATFORMS = frozenset({"cli", "tui", "desktop", ""})+++def _as_flag(raw: Any, default: Optional[bool]) -> Optional[bool]:+ """A config or env value read as a boolean. Unrecognized strings keep ``default``."""+ if isinstance(raw, bool):+ return raw+ if raw is None:+ return default+ if isinstance(raw, str):+ text = raw.strip().lower()+ if text in {"1", "true", "yes", "on"}:+ return True+ if text in {"0", "false", "no", "off", ""}:+ return False+ return default+ return bool(raw)++# (injection.sessionStart name, context key, heading). Render order is fixed here, not by config order._CONTEXT_SECTIONS = (("summary", "summary", "Session Summary"),@@ -161,8 +179,9 @@ class HonchoMemoryProvider(DialecticMixin, MemoryProvider):# Init auth failures live here because the failed manager is discarded.self._init_auth_failure: Optional[str] = Noneself._init_auth_notice_emitted = False- # Set when no user peer could be named (no runtime identity, no peerName); init is not retried.+ # Set when no user peer could be named (no runtime identity, no peerName). Init is not retried.self._init_peer_failure: Optional[str] = None+ self._init_peer_platform: str = "cli"self._init_peer_notice_emitted = Falseself._cron_skipped = False # cron and flush contexts disable the plugin entirely@@ -293,6 +312,7 @@ class HonchoMemoryProvider(DialecticMixin, MemoryProvider):elif isinstance(e, HonchoPeerUnresolvedError):# A missing peerName does not heal mid-session, so drop the deferred kwargs and stop retrying.self._init_peer_failure = str(e)+ self._init_peer_platform = str(dict(init_kwargs).get("platform") or "cli")self._lazy_init_kwargs = self._lazy_init_session_id = Nonelogger.warning("Honcho %s session init failed: %s", label, detail)return False@@ -440,24 +460,22 @@ class HonchoMemoryProvider(DialecticMixin, MemoryProvider):@staticmethoddef _resolve_injection_log_path(look: _HostLookup) -> Optional[str]:"""Where to append the injection audit, or None to keep it off.- The ``logging`` key and HONCHO_LOGGING were both accepted and ignored before this;- they now switch the audit on. HONCHO_INJECTION_LOG overrides the destination."""++ The ``logging`` key or HONCHO_LOGGING switches it on. HONCHO_INJECTION_LOG overrides the destination."""explicit = os.environ.get("HONCHO_INJECTION_LOG")if explicit:return explicit- enabled = look.pick_set("logging")+ enabled = _as_flag(look.pick_set("logging"), default=None)if enabled is None:- enabled = os.environ.get("HONCHO_LOGGING", "").lower() in ("1", "true", "yes")+ enabled = _as_flag(os.environ.get("HONCHO_LOGGING"), default=False)if not enabled:return Nonereturn os.path.join(os.path.expanduser("~"), ".honcho", "injection.log")def _log_injection(self, reason: str, payload: str = "") -> str:- """Append one record of what this turn injected and why, then return ``payload`` unchanged.- The reason matters as much as the bytes: prefetch has several ways to return nothing- (cron, tools mode, session not ready, trivial prompt, fetched-but-empty) and they need- different fixes. The turn number says whether context arrived in time to steer the turn.- Never raises: an audit that can break the agent is worse than no audit."""+ """Append one record of what this turn injected and why, then return ``payload`` unchanged. Never raises.++ The reason is recorded because prefetch has several ways to return nothing and each needs a different fix."""path = self._injection_log_pathif not path:return payload@@ -469,7 +487,9 @@ class HonchoMemoryProvider(DialecticMixin, MemoryProvider):}, ensure_ascii=False)with self._injection_log_lock:os.makedirs(os.path.dirname(path), exist_ok=True)- with open(path, "a", encoding="utf-8") as fh:+ # The record holds the user's representation verbatim, so the file is owner-only.+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)+ with os.fdopen(fd, "a", encoding="utf-8") as fh:fh.write(record + "\n")except Exception as e:logger.debug("Honcho injection log write failed: %s", e)@@ -600,13 +620,27 @@ class HonchoMemoryProvider(DialecticMixin, MemoryProvider):"Tell the user (once) that Honcho memory is paused and that running 'hermes honcho setup' ""to re-authenticate will restore it.")+ def _peer_failure_text(self) -> str:+ """The stored peer failure plus the fix that fits the session's platform.++ On a gateway platform the fix is a user id from the transport, never peerName: a shared+ peerName would merge every user of that gateway onto one peer."""+ text = self._init_peer_failure or ""+ if self._init_peer_platform in _LOCAL_PLATFORMS:+ return f"{text} Set one with 'hermes honcho peer --user <name>'."+ return f"{text} This platform supplied no user id for the chat, so memory stays off here."+def _pop_peer_notice(self) -> str:"""One-time model-facing notice that no user peer could be named and memory is off."""if self._init_peer_failure is None or self._init_peer_notice_emitted:return ""self._init_peer_notice_emitted = True- return (f"[Honcho memory status] Honcho memory is off for this session. {self._init_peer_failure}\n"- "Tell the user (once) that Honcho memory is off until honcho.json names a user peer.")+ if self._init_peer_platform in _LOCAL_PLATFORMS:+ advice = "Tell the user (once) that Honcho memory is off until honcho.json names a user peer."+ else:+ advice = ("Tell the user (once) that Honcho memory is off for this chat. Do not suggest peerName: "+ "on a shared gateway it would merge every user onto one peer.")+ return f"[Honcho memory status] Honcho memory is off for this session. {self._peer_failure_text()}\n{advice}"def _truncate_to_budget(self, text: str) -> str:"""Truncate text to the context_tokens budget (≈4 chars/token) at a word boundary."""@@ -987,7 +1021,9 @@ class HonchoMemoryProvider(DialecticMixin, MemoryProvider):if not self._ensure_session():if self._init_auth_failure:return tool_error(f"Honcho memory authentication failed: {self._init_auth_failure}")- return tool_error(self._init_peer_failure or "Honcho session could not be initialized.")+ if self._init_peer_failure:+ return tool_error(self._peer_failure_text())+ return tool_error("Honcho session could not be initialized.")if not self._manager or not self._session_key:return tool_error("Honcho is not active for this session.")if (handler := self._TOOL_HANDLERS.get(tool_name)) is None:@@ -1002,13 +1038,12 @@ class HonchoMemoryProvider(DialecticMixin, MemoryProvider):logger.error("Honcho tool %s failed: %s", tool_name, e)return tool_error(f"Honcho {tool_name} failed: {e}")- # Shutdown never joins for less than this; a thread blocked in httpx can hold the HTTP timeout.+ # Shutdown never joins for less than this. A thread blocked in httpx can hold the HTTP timeout._SHUTDOWN_JOIN_FLOOR = 5.0def _shutdown_join_budget(self) -> float:"""One join window for every plugin thread: the floor, or the configured HTTP timeout when- that is longer, so a thread blocked in a Honcho call can finish before the interpreter- finalizes (#33485)."""+ that is longer, so a thread blocked in a Honcho call can finish before the interpreter finalizes."""try:from plugins.memory.honcho.client_cache import _resolve_timeout_from_sourcesreturn max(self._SHUTDOWN_JOIN_FLOOR, _resolve_timeout_from_sources(self._config))@@ -1018,7 +1053,7 @@ class HonchoMemoryProvider(DialecticMixin, MemoryProvider):def shutdown(self) -> None:"""Join the write threads, flush and stop the manager, then join every other thread thisprovider or its manager spawned, all within one budget. A daemon thread still blocked in- httpx I/O when the interpreter finalizes aborts the process (#37632)."""+ httpx I/O when the interpreter finalizes aborts the process."""self._recall_generation = object()budget = self._shutdown_join_budget()deadline = time.monotonic() + budget@@ -1029,10 +1064,11 @@ class HonchoMemoryProvider(DialecticMixin, MemoryProvider):if manager and not (self._init_thread and self._init_thread.is_alive() and not self._session_initialized):# saveMessages: false skips persistence, but the async-writer thread must still be joined.with contextlib.suppress(Exception):+ remaining = max(0.0, deadline - time.monotonic())if getattr(self._config, "save_messages", True):- manager.shutdown() # flush_all() + join the writer+ manager.shutdown(timeout=remaining) # flush_all() + join the writerelse:- manager.stop_async_writer()+ manager.stop_async_writer(timeout=remaining)left = join_plugin_threads((self, manager), timeout=max(0.0, deadline - time.monotonic()))if left:logger.warning("Honcho shutdown timed out after %.1fs with %d thread(s) still running: %s",diff --git a/plugins/memory/honcho/client.py b/plugins/memory/honcho/client.pyindex c60bab62881..0469e62fe2c 100644--- a/plugins/memory/honcho/client.py+++ b/plugins/memory/honcho/client.py@@ -511,8 +511,7 @@ class HonchoClientConfig:return self.workspace_id-# Threads the plugin spawned, keyed by the provider or manager that owns them: shutdown joins its own-# threads with one budget and never waits on another agent's work in the same gateway process.+# Threads keyed by the provider or manager that owns them, so shutdown never waits on another agent's work._plugin_threads: "weakref.WeakKeyDictionary[Any, weakref.WeakSet]" = weakref.WeakKeyDictionary()_plugin_threads_lock = _threading.Lock()diff --git a/plugins/memory/honcho/session.py b/plugins/memory/honcho/session.pyindex ea157d936b6..4376737bfba 100644--- a/plugins/memory/honcho/session.py+++ b/plugins/memory/honcho/session.py@@ -27,9 +27,7 @@ _ASYNC_SHUTDOWN = object()# Sessions remembered in _joined_author_peers; the oldest is dropped past this and its authors rejoin on their next write._SESSION_CACHE_MAX_SIZE = 128-# Honcho persists every message durably and get_or_create() re-hydrates from it on a cache miss,-# so the local copies are bounded: synced messages beyond the retention cap are trimmed after a-# flush, and sessions idle past the TTL are evicted (next use costs one extra round trip).+# Honcho persists every message and get_or_create() re-hydrates on a miss, so the local copies stay bounded._SESSION_MESSAGE_RETENTION = 200_SESSION_IDLE_TTL_SECONDS = 3600_SESSION_SWEEP_INTERVAL_SECONDS = 300@@ -50,7 +48,7 @@ class HonchoSession:created_at: datetime = field(default_factory=datetime.now)updated_at: datetime = field(default_factory=datetime.now)metadata: dict[str, Any] = field(default_factory=dict)- # Held by _flush_session across select, send and the _synced flip; lives with the message list it guards.+ # Held by _flush_session across select, send and the _synced flip. It lives with the message list it guards._flush_lock: threading.RLock = field(default_factory=threading.RLock, repr=False, compare=False)def add_message(self, role: str, content: str, **kwargs: Any) -> None:@@ -100,8 +98,7 @@ class HonchoSessionManager(SessionAuthMixin, SessionPeersMixin, SessionContextMi):setattr(self, f"_{name}", getattr(config, name) if config else default)self._turn_counter: int = 0- # honcho session id -> observation booleans synced from that session's server config.- # Whole-dict values are swapped in one assignment, so lock-free readers never see a partial one.+ # honcho session id -> observation booleans. Whole dicts are swapped in one assignment, so readers never see a partial one.self._session_observation: dict[str, dict[str, bool]] = {}# Prefetch cache: session_key -> last context result (consumed once per turn).@@ -247,12 +244,13 @@ class HonchoSessionManager(SessionAuthMixin, SessionPeersMixin, SessionContextMidef _get_or_create_honcho_session(self, session_id: str, user_peer: Any, assistant_peer: Any,) -> tuple[Any, list, dict[str, bool] | None]:- """(honcho_session, existing_messages, observation flags) with peers configured; a cached- session yields no messages and no flags."""+ """(honcho_session, existing_messages, observation flags) with peers configured.++ A cached session yields no messages and the flags stored when it was configured."""with self._cache_lock:if session_id in self._sessions_cache:logger.debug("Honcho session '%s' retrieved from cache", session_id)- return self._sessions_cache[session_id], [], None+ return self._sessions_cache[session_id], [], self._session_observation.get(session_id)self._authed_call("session setup", lambda: self._sdk_session(session_id))observation = self._configure_session_peers(session_id, user_peer, assistant_peer)@@ -267,7 +265,7 @@ class HonchoSessionManager(SessionAuthMixin, SessionPeersMixin, SessionContextMi@staticmethoddef _has_unsynced(session: HonchoSession) -> bool:- return any(not m.get("_synced") for m in session.messages)+ return any(not m.get("_synced") for m in list(session.messages))def _evict_session_locked(self, key: str, session: HonchoSession) -> None:"""Drop one session and every entry keyed to it. Caller holds _cache_lock."""@@ -402,9 +400,9 @@ class HonchoSessionManager(SessionAuthMixin, SessionPeersMixin, SessionContextMiexcess -= 1def _flush_session(self, session: HonchoSession) -> bool:- """Write unsynced messages to Honcho synchronously. The session's lock serializes flushers of- one message list: the async writer and an exit-time flush_all() both pick up the same batch- otherwise, and the second one enters here only after the first marked it synced."""+ """Write unsynced messages to Honcho synchronously.++ The session's lock keeps the async writer and an exit-time flush_all() from posting the same batch."""with session._flush_lock:return self._flush_session_locked(session)@@ -419,7 +417,11 @@ class HonchoSessionManager(SessionAuthMixin, SessionPeersMixin, SessionContextMiassistant_peer = self._get_or_create_peer(session.assistant_peer_id)honcho_session = self._sessions_cache.get(session.honcho_session_id)if honcho_session is None:- honcho_session, _, _ = self._get_or_create_honcho_session(session.honcho_session_id, user_peer, assistant_peer)+ honcho_session, _, observation = self._get_or_create_honcho_session(+ session.honcho_session_id, user_peer, assistant_peer)+ if observation is not None:+ with self._cache_lock:+ self._session_observation[session.honcho_session_id] = observationhoncho_messages = []for m in new_messages:if m["role"] != "user":@@ -441,7 +443,9 @@ class HonchoSessionManager(SessionAuthMixin, SessionPeersMixin, SessionContextMifor msg in new_messages:msg["_synced"] = okif ok:- self._trim_synced_messages(session)+ # Under the cache lock so the eviction check never iterates a list being trimmed.+ with self._cache_lock:+ self._trim_synced_messages(session)return okdef _try_flush(self, session: HonchoSession, level: int, msg: str) -> bool:@@ -469,19 +473,36 @@ class HonchoSessionManager(SessionAuthMixin, SessionPeersMixin, SessionContextMiexcept Exception as e:logger.error("Honcho async writer error: %s", e)+ def _keep_until_flushed(self, session: HonchoSession) -> None:+ """Put an evicted session that still holds unsynced messages back where flush_all() looks.++ When a newer object already owns the key, this one's batch is written now instead."""+ with self._cache_lock:+ current = self._cache.get(session.key)+ if current is session or not self._has_unsynced(session):+ return+ if current is None:+ self._cache[session.key] = session+ return+ self._flush_session(session)+def save(self, session: HonchoSession) -> None:- """Save messages per write_frequency: "async" enqueues for the background thread; "turn"- flushes now; "session" defers until flush_all(); int N flushes every N turns."""+ """Save messages per write_frequency: "async" enqueues for the background thread, "turn"+ flushes now, "session" defers until flush_all(), int N flushes every N turns."""self._turn_counter += 1wf = self._write_frequency- if self._shutting_down:+ if wf == "async" and self._async_queue is not None:+ # Under the writer lock, so a put cannot slip in after stop_async_writer() drained the queue.+ with self._async_thread_lock:+ if not self._shutting_down:+ self._ensure_async_writer_locked()+ self._async_queue.put(session)+ returnself._flush_session(session)- elif wf == "async":- if self._async_queue is not None:- self._ensure_async_writer()- self._async_queue.put(session)- elif wf == "turn" or (isinstance(wf, int) and wf > 0 and self._turn_counter % wf == 0):+ elif self._shutting_down or wf == "turn" or (isinstance(wf, int) and wf > 0 and self._turn_counter % wf == 0):self._flush_session(session)+ else:+ self._keep_until_flushed(session)def flush_all(self) -> None:"""Flush unsynced messages for all cached sessions, then drain the async queue inline."""@@ -492,38 +513,48 @@ class HonchoSessionManager(SessionAuthMixin, SessionPeersMixin, SessionContextMiself._flush_session(session)except Exception as e:logger.error("Honcho flush_all error for %s: %s", session.key, e)+ self._drain_async_queue()- if self._async_queue is not None:- while not self._async_queue.empty():- try:- item = self._async_queue.get_nowait()- if item is not _ASYNC_SHUTDOWN:- self._flush_session(item)- except queue.Empty:- break+ def _drain_async_queue(self) -> None:+ if self._async_queue is None:+ return+ while not self._async_queue.empty():+ try:+ item = self._async_queue.get_nowait()+ if item is not _ASYNC_SHUTDOWN:+ self._flush_session(item)+ except queue.Empty:+ breakdef _ensure_async_writer(self) -> None:"""Start the async writer on first enqueue (idempotent, thread-safe)."""if self._async_thread is not None and self._async_thread.is_alive():returnwith self._async_thread_lock:- if self._async_thread is None or not self._async_thread.is_alive():- self._async_thread = spawn_context_thread(self._async_writer_loop, name="honcho-async-writer", owner=self)- self._async_thread.start()+ self._ensure_async_writer_locked()- def stop_async_writer(self) -> None:- """Join the async writer WITHOUT flushing (saveMessages: false must still exit cleanly)."""- self._shutting_down = True+ def _ensure_async_writer_locked(self) -> None:+ if self._async_thread is None or not self._async_thread.is_alive():+ self._async_thread = spawn_context_thread(self._async_writer_loop, name="honcho-async-writer", owner=self)+ self._async_thread.start()++ def stop_async_writer(self, timeout: float = 10.0) -> None:+ """Join the async writer, then drain whatever was queued before the join.++ saveMessages: false never enqueues, so the drain is a no-op there and the exit stays clean."""+ with self._async_thread_lock:+ self._shutting_down = Trueif self._async_queue is not None and self._async_thread is not None and self._async_thread.is_alive():self._async_queue.put(_ASYNC_SHUTDOWN)- self._async_thread.join(timeout=10)+ self._async_thread.join(timeout=timeout)+ self._drain_async_queue()- def shutdown(self) -> None:+ def shutdown(self, timeout: float = 10.0) -> None:"""Flush everything, then stop the async writer thread."""self._shutting_down = Trueif self._async_queue is not None:self.flush_all()- self.stop_async_writer()+ self.stop_async_writer(timeout=timeout)# ----- Prefetch cache -----diff --git a/plugins/memory/honcho/session_context.py b/plugins/memory/honcho/session_context.pyindex c39fb42d395..3185aa340d4 100644--- a/plugins/memory/honcho/session_context.py+++ b/plugins/memory/honcho/session_context.py@@ -12,7 +12,7 @@ logger = logging.getLogger("plugins.memory.honcho.session")_FAILED = object() # sentinel: a guarded call raised (distinct from a legitimately empty/None result)-# Reasoning-channel markers a summarizer model can leave inside a persisted session summary (#97639).+# Reasoning-channel markers a summarizer model can leave inside a persisted session summary._THINK_BLOCK_RE = re.compile(r"<\s*(?:think|thinking|reasoning|thought|reasoning_scratchpad)\s*>.*?"r"<\s*/\s*(?:think|thinking|reasoning|thought|reasoning_scratchpad)\s*>",diff --git a/plugins/memory/honcho/session_peers.py b/plugins/memory/honcho/session_peers.pyindex 5138904c9f0..6fa0c9c6c10 100644--- a/plugins/memory/honcho/session_peers.py+++ b/plugins/memory/honcho/session_peers.py@@ -104,7 +104,7 @@ class SessionPeersMixin:return self._sanitize_id(peer_name)raise HonchoPeerUnresolvedError(f"Honcho has no user peer for session '{key}': the transport supplied no user identity and "- "honcho.json declares no peerName. Set one with 'hermes honcho peer --user <name>'.")+ "honcho.json declares no peerName.")def _resolve_peer_id(self, session: HonchoSession, peer: str | None) -> str:"""Resolve a peer alias ('user'/'ai') or explicit peer ID to a concrete, non-empty peer ID."""diff --git a/tests/honcho_plugin/test_async_memory.py b/tests/honcho_plugin/test_async_memory.pyindex ec25a611152..9256b4da4f6 100644--- a/tests/honcho_plugin/test_async_memory.py+++ b/tests/honcho_plugin/test_async_memory.py@@ -354,6 +354,39 @@ class TestAsyncWriterThread:# async retry on failure# ---------------------------------------------------------------------------+class TestStopAsyncWriterDrain:+ def test_items_queued_before_the_join_are_flushed(self, make_manager):+ mgr = make_manager("async")+ flushed = []+ mgr._flush_session = lambda s: flushed.append(s.key) or True+ mgr._async_queue.put(_make_session(key="late"))++ mgr.stop_async_writer()++ assert flushed == ["late"]+ assert mgr._async_queue.empty()++ def test_save_after_the_writer_stopped_flushes_inline(self, make_manager):+ mgr = make_manager("async")+ flushed = []+ mgr._flush_session = lambda s: flushed.append(s.key) or True+ mgr.stop_async_writer()++ mgr.save(_make_session(key="after"))++ assert flushed == ["after"]+ assert mgr._async_queue.empty()++ def test_shutdown_passes_the_join_timeout_through(self, make_manager, monkeypatch):+ mgr = make_manager("async")+ seen = {}+ monkeypatch.setattr(mgr, "stop_async_writer", lambda timeout=10.0: seen.setdefault("timeout", timeout))++ mgr.shutdown(timeout=2.5)++ assert seen["timeout"] == 2.5++class TestAsyncWriterRetry:def test_retries_once_on_failure(self, make_manager):mgr = make_manager(write_frequency="async")diff --git a/tests/honcho_plugin/test_session.py b/tests/honcho_plugin/test_session.pyindex 21da347f727..111482353cf 100644--- a/tests/honcho_plugin/test_session.py+++ b/tests/honcho_plugin/test_session.py@@ -1,6 +1,7 @@"""Tests for plugins/memory/honcho/session.py — HonchoSession and helpers."""import json+import osimport sysimport threadingimport time@@ -9,6 +10,8 @@ from datetime import datetimefrom types import SimpleNamespacefrom unittest.mock import MagicMock, patch+import pytest+from plugins.memory.honcho.session import (HonchoSession,HonchoSessionManager,@@ -1335,7 +1338,7 @@ class TestSessionStartInjection:# ----------------------------------------------------------------------------# the logging key switches on the injection audit; it is off by default and never raises+# the logging key switches on the injection audit. It is off by default and never raises# ---------------------------------------------------------------------------@@ -1356,6 +1359,29 @@ class TestInjectionAuditLog:raw = {"logging": True, "hosts": {"hermes": {"logging": False}}}assert _provider_with_raw(raw)._injection_log_path is None+ @pytest.mark.parametrize("value", ["false", "0", "no", "off", ""])+ def test_string_false_values_keep_it_off(self, monkeypatch, value):+ monkeypatch.delenv("HONCHO_LOGGING", raising=False)+ monkeypatch.delenv("HONCHO_INJECTION_LOG", raising=False)+ assert _provider_with_raw({"logging": value})._injection_log_path is None++ @pytest.mark.parametrize("value", ["true", "1", "yes", "on"])+ def test_string_true_values_switch_it_on(self, monkeypatch, value):+ monkeypatch.delenv("HONCHO_INJECTION_LOG", raising=False)+ assert _provider_with_raw({"logging": value})._injection_log_path is not None++ def test_env_off_value_keeps_it_off(self, monkeypatch):+ monkeypatch.setenv("HONCHO_LOGGING", "off")+ monkeypatch.delenv("HONCHO_INJECTION_LOG", raising=False)+ assert _provider_with_raw({})._injection_log_path is None++ @pytest.mark.skipif(os.name == "nt", reason="POSIX file modes")+ def test_log_file_is_owner_only(self, tmp_path):+ provider = _provider_with_raw({})+ provider._injection_log_path = str(tmp_path / "injection.log")+ provider._log_injection("injected", "payload")+ assert (tmp_path / "injection.log").stat().st_mode & 0o777 == 0o600+def test_explicit_path_env_overrides_destination(self, monkeypatch, tmp_path):monkeypatch.setenv("HONCHO_INJECTION_LOG", str(tmp_path / "audit.log"))assert _provider_with_raw({})._injection_log_path == str(tmp_path / "audit.log")diff --git a/tests/test_honcho_session_cache_bounds.py b/tests/test_honcho_session_cache_bounds.pyindex afd5ae2795a..2c034b962e9 100644--- a/tests/test_honcho_session_cache_bounds.py+++ b/tests/test_honcho_session_cache_bounds.py@@ -291,3 +291,69 @@ def test_flush_does_not_resurrect_an_evicted_session():assert mgr._flush_session(session) is Trueassert "gone" not in mgr._cacheassert all(m["_synced"] for m in session.messages)+++def _sdk_session():+ return SimpleNamespace(add_messages=lambda messages: None)+++def test_flush_that_recreates_the_sdk_session_stores_its_observation_flags():+ """After an eviction the flush path rebuilds the SDK session. The flags it configured must be kept."""+ mgr = _manager()+ session = _session(key="back")+ session.add_message("user", "hello", _synced=False)+ flags = {"user_observe_me": False, "user_observe_others": True, "ai_observe_me": True, "ai_observe_others": False}+ mgr._get_or_create_peer = lambda peer_id: SimpleNamespace(message=lambda content: content)+ mgr._get_or_create_honcho_session = lambda sid, user, assistant: (_sdk_session(), [], flags)++ assert mgr._flush_session(session) is True+ assert mgr._session_observation[session.honcho_session_id] == flags+++def test_cached_sdk_session_returns_the_flags_stored_for_it():+ mgr = _manager()+ flags = {"user_observe_me": True, "user_observe_others": False, "ai_observe_me": True, "ai_observe_others": True}+ sdk = _sdk_session()+ mgr._sessions_cache["hs-x"] = sdk+ mgr._session_observation["hs-x"] = flags++ assert mgr._get_or_create_honcho_session("hs-x", None, None) == (sdk, [], flags)+++def test_deferred_save_puts_an_evicted_session_back_in_the_cache():+ """write_frequency "session" defers to flush_all(), which only sees cached sessions."""+ mgr = _manager()+ mgr._write_frequency = "session"+ session = _session(key="evicted")+ session.add_message("user", "unsynced", _synced=False)++ mgr.save(session)++ assert mgr._cache["evicted"] is session+++def test_deferred_save_of_a_fully_synced_evicted_session_stays_out_of_the_cache():+ mgr = _manager()+ mgr._write_frequency = "session"+ session = _session(key="done")+ session.add_message("user", "old", _synced=True)++ mgr.save(session)++ assert "done" not in mgr._cache+++def test_deferred_save_flushes_inline_when_a_newer_object_owns_the_key():+ mgr = _manager()+ mgr._write_frequency = "session"+ newer = _session(key="k")+ mgr._cache["k"] = newer+ stale = _session(key="k")+ stale.add_message("user", "late", _synced=False)+ flushed = []+ mgr._flush_session = lambda s: flushed.append(s) or True++ mgr.save(stale)++ assert flushed == [stale]+ assert mgr._cache["k"] is newerdiff --git a/tests/test_honcho_startup_fail_open.py b/tests/test_honcho_startup_fail_open.pyindex f850f8bb8b6..3856a0bd7c8 100644--- a/tests/test_honcho_startup_fail_open.py+++ b/tests/test_honcho_startup_fail_open.py@@ -283,8 +283,8 @@ def test_honcho_tools_eager_init_failure_does_not_leave_ready_manager(monkeypatcassert provider._manager is None-def _init_with_unresolved_peer(monkeypatch, cfg) -> tuple[HonchoMemoryProvider, list[int]]:- """Provider whose session init fails because no user peer can be named; returns the attempt log."""+def _init_with_unresolved_peer(monkeypatch, cfg, platform: str = "cli") -> tuple[HonchoMemoryProvider, list[int]]:+ """Provider whose session init fails because no user peer can be named. Returns the attempt log."""from plugins.memory.honcho.session_peers import HonchoPeerUnresolvedErrorprovider = HonchoMemoryProvider()@@ -296,7 +296,7 @@ def _init_with_unresolved_peer(monkeypatch, cfg) -> tuple[HonchoMemoryProvider,raise HonchoPeerUnresolvedError("Honcho has no user peer for session 'x': honcho.json declares no peerName.")monkeypatch.setattr(HonchoMemoryProvider, "_do_session_init", no_peer)- provider.initialize("session-1", platform="cli")+ provider.initialize("session-1", platform=platform)if provider._init_thread:provider._init_thread.join(timeout=5)return provider, attempts@@ -324,9 +324,31 @@ def test_honcho_unresolved_peer_tool_error_names_the_fix(monkeypatch):result = json.loads(provider.handle_tool_call("honcho_profile", {"peer": "user"}))assert "peerName" in result["error"]+ assert "hermes honcho peer --user" in result["error"]assert "could not be initialized" not in result["error"]+def test_honcho_unresolved_peer_on_a_gateway_platform_does_not_recommend_peer_name(monkeypatch):+ """A shared peerName on a multi-user gateway would merge every human onto one peer."""+ provider, _ = _init_with_unresolved_peer(monkeypatch, _configured_hybrid_config(), platform="telegram")++ notice = provider.prefetch("what did we decide about the schema?")++ assert "Honcho memory is off" in notice+ assert "hermes honcho peer --user" not in notice+ assert "Do not suggest peerName" in notice+++def test_honcho_unresolved_peer_tool_error_on_a_gateway_platform_omits_the_peer_name_fix(monkeypatch):+ cfg = _configured_tools_config(init_on_session_start=True)+ provider, _ = _init_with_unresolved_peer(monkeypatch, cfg, platform="discord")++ result = json.loads(provider.handle_tool_call("honcho_profile", {"peer": "user"}))++ assert "hermes honcho peer --user" not in result["error"]+ assert "supplied no user id" in result["error"]++def test_honcho_tools_lazy_hooks_do_not_prestart_background_init(monkeypatch):"""tools lazy mode lets the first tool call own session initialization."""provider = HonchoMemoryProvider()diff --git a/tests/test_tui_gateway_server.py b/tests/test_tui_gateway_server.pyindex e47d9ec7378..e3c413a9816 100644--- a/tests/test_tui_gateway_server.py+++ b/tests/test_tui_gateway_server.py@@ -4564,14 +4564,26 @@ def _capture_make_agent_kwargs(monkeypatch) -> dict:def test_make_agent_passes_the_authenticated_dashboard_user_as_user_id(monkeypatch):"""The identity stamped at WS-upgrade auth (WSTransport.auth_identity) reaches the agent as- ``user_id``, the same kwarg gateways pass, so memory providers scope memory to the login (#89794)."""+ ``user_id``, the same kwarg gateways pass, so memory providers scope memory to the login."""captured = _capture_make_agent_kwargs(monkeypatch)transport = types.SimpleNamespace(auth_identity={"user_id": "oidc|abc123", "provider": "oidc"})monkeypatch.setitem(server._sessions, "sid-auth", {"session_key": "k", "transport": transport})server._make_agent("sid-auth", "k")- assert captured["user_id"] == "oidc|abc123"+ assert captured["user_id"] == "oidc:oidc|abc123"+++def test_make_agent_keeps_same_named_users_of_two_login_providers_apart(monkeypatch):+ """A basic-auth ``alice`` and an OIDC ``alice`` are two people and must not share one memory peer."""+ seen = []+ for provider in ("basic", "oidc"):+ captured = _capture_make_agent_kwargs(monkeypatch)+ transport = types.SimpleNamespace(auth_identity={"user_id": "alice", "provider": provider})+ monkeypatch.setitem(server._sessions, f"sid-{provider}", {"session_key": "k", "transport": transport})+ server._make_agent(f"sid-{provider}", "k")+ seen.append(captured["user_id"])+ assert seen == ["basic:alice", "oidc:alice"]@pytest.mark.parametrize("identity", [@@ -4581,7 +4593,7 @@ def test_make_agent_passes_the_authenticated_dashboard_user_as_user_id(monkeypat{"user_id": "abc", "provider": ""},])def test_make_agent_passes_no_user_id_without_an_authenticated_human(monkeypatch, identity):- """Legacy token, stdio and the PTY child's server-internal credential name no human; the+ """Legacy token, stdio and the PTY child's server-internal credential name no human. Theagent must not receive a user id memory would treat as a person."""captured = _capture_make_agent_kwargs(monkeypatch)transport = types.SimpleNamespace(auth_identity=identity)diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex b65198277ef..aba4a77e8ca 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -2256,11 +2256,13 @@ def _startup_system_prompt(cfg: dict, task_id: str) -> str:def _session_auth_user_id(session: dict | None) -> str | None:- """User id the WS-upgrade credential authenticated for ``session``'s transport, or None for the legacy- token, stdio, and the server-internal credential the PTY child connects with."""+ """``<provider>:<user id>`` the WS-upgrade credential authenticated for ``session``'s transport.++ None for the legacy token, stdio, and the server-internal credential the PTY child connects with.+ The provider prefix keeps a basic-auth ``alice`` and an OIDC ``alice`` apart."""identity = getattr((session or {}).get("transport"), "auth_identity", None)if _methods_browser_control._is_authenticated_identity(identity):- return str(identity["user_id"]).strip()+ return f"{str(identity['provider']).strip()}:{str(identity['user_id']).strip()}"return Nonediff --git a/tui_gateway/ws.py b/tui_gateway/ws.pyindex 0ab7ede75f8..2f8d52c215a 100644--- a/tui_gateway/ws.py+++ b/tui_gateway/ws.py@@ -92,7 +92,7 @@ class WSTransport:self._ws = wsself._loop = loopself._peer = peer- #: Server-verified identity from the WS-upgrade credential, stamped by ``web_server._ws_auth_reason``; None+ #: Server-verified identity from the WS-upgrade credential, stamped by ``web_server_chat._ws_auth_reason``; None#: for legacy-token/stdio. RPC params can never populate it: sole identity authority for browser controllers#: and for the ``user_id`` the agent is built with (``server._session_auth_user_id``).self.auth_identity = auth_identity