Local-first 🧠 memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.
TypeScript
"""Tests for the native Hermes memory provider and its bridge.
The provider subclasses the Hermes ``MemoryProvider`` ABC when running inside
a Hermes install, and a local fallback base otherwise (so this repo's CI can
exercise it without Hermes present). All deterministic work is delegated to
the TypeScript core through a ``BrainBridge`` seam, which tests replace with a
fake so no live Bun runtime is needed.
"""
import contextlib
import io
import json
import os
import sys
import tempfile
import threading
import time
import unittest
from pathlib import Path
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[2]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from plugins.hermes import config as cfg # noqa: E402
from plugins.hermes._base import ( # noqa: E402
HAS_HERMES_ABC,
MemoryProvider,
_FallbackMemoryProviderBase,
)
from plugins.hermes import bridge as bridge_module # noqa: E402
from plugins.hermes.bridge import ( # noqa: E402
DEFAULT_REQUEST_TIMEOUT_SECONDS,
REQUEST_TIMEOUT_ENV,
BridgeError,
BridgeTimeoutError,
BridgeTransportError,
FakeBrainBridge,
JsonRpcStdioClient,
McpBrainBridge,
resolve_request_timeout,
)
from plugins.hermes import provider as provider_module # noqa: E402
from plugins.hermes.provider import ( # noqa: E402
MEMORY_TOOLS,
OpenSecondBrainMemoryProvider,
_find_executable,
_reset_shared_bridges_for_tests,
)
from plugins.hermes.cli import register_cli # noqa: E402
# Every environment variable that can shadow a config field, named by the
# module that reads it. A test class that clears one of these and not the
# others passes or fails on the developer's shell; the tuple was copied into
# five classes and had already drifted from the resolvers - `VAULT_TIMEZONE`
# was in none of them.
_CONFIG_ENV_KEYS = (
cfg.AGENT_NAME_ENV,
cfg.VAULT_DIR_ENV,
cfg.TIMEZONE_ENV,
cfg.CONFIG_PATH_ENV,
cfg.REQUEST_TIMEOUT_ENV,
)
class ConfigHelperTests(unittest.TestCase):
_ENV_KEYS = _CONFIG_ENV_KEYS
def setUp(self):
self._saved = {k: os.environ.pop(k, None) for k in self._ENV_KEYS}
cfg._reset_template_cache_for_tests()
def tearDown(self):
for k in self._ENV_KEYS:
os.environ.pop(k, None)
if self._saved[k] is not None:
os.environ[k] = self._saved[k]
cfg._reset_template_cache_for_tests()
def _write_config(self, tmp, body):
path = Path(tmp) / "config.yaml"
path.write_text(body, encoding="utf-8")
os.environ["OPEN_SECOND_BRAIN_CONFIG"] = str(path)
return path
def test_resolve_agent_name_prefers_env(self):
os.environ["VAULT_AGENT_NAME"] = "env-agent"
self.assertEqual(cfg.resolve_agent_name(), "env-agent")
def test_resolve_agent_name_from_config_snake_and_camel(self):
with tempfile.TemporaryDirectory() as tmp:
self._write_config(tmp, 'agent_name: "snake-agent"\n')
self.assertEqual(cfg.resolve_agent_name(), "snake-agent")
with tempfile.TemporaryDirectory() as tmp:
self._write_config(tmp, 'agentName: "camel-agent"\n')
self.assertEqual(cfg.resolve_agent_name(), "camel-agent")
def test_resolve_agent_name_default_when_unresolved(self):
with tempfile.TemporaryDirectory() as tmp:
os.environ["OPEN_SECOND_BRAIN_CONFIG"] = str(Path(tmp) / "missing.yaml")
self.assertEqual(cfg.resolve_agent_name(), cfg.DEFAULT_AGENT)
def test_resolve_vault_prefers_env(self):
os.environ["VAULT_DIR"] = "/tmp/env-vault"
self.assertEqual(cfg.resolve_vault(), "/tmp/env-vault")
def test_resolve_vault_from_config(self):
with tempfile.TemporaryDirectory() as tmp:
self._write_config(tmp, 'vault: "/tmp/cfg-vault"\nagent_name: "x"\n')
self.assertEqual(cfg.resolve_vault(), "/tmp/cfg-vault")
def test_resolve_vault_none_when_unset(self):
with tempfile.TemporaryDirectory() as tmp:
self._write_config(tmp, 'agent_name: "x"\n')
self.assertIsNone(cfg.resolve_vault())
def test_render_reminder_substitutes_every_placeholder(self):
rendered = cfg.render_reminder("zed")
self.assertIn("@zed", rendered)
self.assertNotIn("{agent}", rendered)
def test_build_reminder_none_when_unresolved(self):
with tempfile.TemporaryDirectory() as tmp:
os.environ["OPEN_SECOND_BRAIN_CONFIG"] = str(Path(tmp) / "missing.yaml")
self.assertIsNone(cfg.build_reminder())
def test_build_reminder_string_when_identity_set(self):
os.environ["VAULT_AGENT_NAME"] = "build-agent"
reminder = cfg.build_reminder()
self.assertIsNotNone(reminder)
self.assertIn("@build-agent", reminder)
class FallbackBaseTests(unittest.TestCase):
"""Pin the no-op stand-in contract.
These tests target ``_FallbackMemoryProviderBase`` directly so they hold in
both environments: CI without the Hermes ABC, and a real install where
``MemoryProvider`` aliases the Hermes ABC (which enforces its abstract
surface). The stand-in is the unit under test, not whichever base
``MemoryProvider`` resolves to at import time.
"""
def test_fallback_base_is_subclassable_without_abstract_methods(self):
class Demo(_FallbackMemoryProviderBase):
@property
def name(self):
return "demo"
demo = Demo()
self.assertEqual(demo.name, "demo")
def test_optional_hooks_are_noop_on_fallback_base(self):
class Demo(_FallbackMemoryProviderBase):
@property
def name(self):
return "demo"
demo = Demo()
# Optional lifecycle hooks the provider may not override must not raise.
self.assertIsNone(demo.queue_prefetch("q"))
self.assertIsNone(demo.on_session_end([]))
self.assertIsNone(demo.shutdown())
def test_memory_provider_aliases_fallback_base_without_hermes(self):
# When the Hermes ABC is unavailable, MemoryProvider must BE the
# fallback stand-in (not a separate class), so the provider subclass
# inherits the no-op hooks. With Hermes present, MemoryProvider is the
# real ABC and the stand-in stays independently testable above.
if not HAS_HERMES_ABC:
self.assertIs(MemoryProvider, _FallbackMemoryProviderBase)
else:
self.assertIsNot(MemoryProvider, _FallbackMemoryProviderBase)
class ProviderRequiredSurfaceTests(unittest.TestCase):
_ENV_KEYS = _CONFIG_ENV_KEYS
def setUp(self):
self._saved = {k: os.environ.pop(k, None) for k in self._ENV_KEYS}
def tearDown(self):
for k in self._ENV_KEYS:
os.environ.pop(k, None)
if self._saved[k] is not None:
os.environ[k] = self._saved[k]
def _provider(self, bridge):
return OpenSecondBrainMemoryProvider(bridge=bridge)
def test_name(self):
self.assertEqual(self._provider(FakeBrainBridge()).name, "open-second-brain")
def test_is_available_true_when_vault_configured(self):
os.environ["VAULT_DIR"] = "/tmp/vault"
self.assertTrue(self._provider(FakeBrainBridge()).is_available())
def test_is_available_false_when_no_vault(self):
with tempfile.TemporaryDirectory() as tmp:
os.environ["OPEN_SECOND_BRAIN_CONFIG"] = str(Path(tmp) / "missing.yaml")
self.assertFalse(self._provider(FakeBrainBridge()).is_available())
def test_initialize_starts_bridge(self):
bridge = FakeBrainBridge()
provider = self._provider(bridge)
provider.initialize("sess-1", hermes_home="/tmp/hh")
self.assertTrue(bridge.started)
def test_get_tool_schemas_filters_to_allowlist(self):
bridge = FakeBrainBridge(
tools=[
{"name": "brain_query"},
{"name": "brain_note"},
{"name": "vault_health"},
{"name": "second_brain_status"},
]
)
provider = self._provider(bridge)
provider.initialize("s", hermes_home="/tmp/hh")
names = {t["name"] for t in provider.get_tool_schemas()}
self.assertEqual(names, {"brain_query", "brain_note"})
self.assertTrue(names.issubset(set(MEMORY_TOOLS)))
def test_handle_tool_call_forwards_to_bridge(self):
bridge = FakeBrainBridge(results={"brain_note": {"ok": True}})
provider = self._provider(bridge)
provider.initialize("s", hermes_home="/tmp/hh")
result = provider.handle_tool_call("brain_note", {"text": "hi"})
# Hermes feeds the return back as tool-message content, so the
# contract is str, not dict. The MCP result is serialized losslessly.
self.assertIsInstance(result, str)
self.assertEqual(json.loads(result), {"ok": True})
self.assertEqual(bridge.calls, [("brain_note", {"text": "hi"})])
def test_handle_tool_call_always_returns_string_for_dict_results(self):
# The base-class contract types handle_tool_call as -> str. A raw dict
# reaching the model as tool content breaks strict providers (DeepSeek
# HTTP 400) while passing on lenient ones (Anthropic), so the boundary
# must coerce regardless of the tool's result shape.
shapes = {
"brain_note": {"content": [{"type": "text", "text": "ok"}], "structuredContent": {"ok": True}},
"brain_query": {"structuredContent": {"hits": [1, 2, 3]}},
"brain_search": {},
}
bridge = FakeBrainBridge(results=shapes)
provider = self._provider(bridge)
provider.initialize("s", hermes_home="/tmp/hh")
for tool, shape in shapes.items():
result = provider.handle_tool_call(tool, {})
self.assertIsInstance(result, str, f"{tool} must return a string")
# Lossless: both the content and structuredContent envelopes survive.
self.assertEqual(json.loads(result), shape)
def test_handle_tool_call_passes_through_string_result(self):
# A bridge that already yields a string must not be double-encoded.
bridge = FakeBrainBridge(results={"brain_note": "plain text"})
provider = self._provider(bridge)
provider.initialize("s", hermes_home="/tmp/hh")
self.assertEqual(provider.handle_tool_call("brain_note", {}), "plain text")
def test_get_config_schema_shape(self):
schema = self._provider(FakeBrainBridge()).get_config_schema()
by_key = {f["key"]: f for f in schema}
self.assertEqual(set(by_key), {"vault", "agent_name", "timezone"})
self.assertTrue(by_key["vault"].get("required"))
def test_save_config_writes_to_osb_config_and_preserves_others(self):
with tempfile.TemporaryDirectory() as tmp:
cfg_path = Path(tmp) / "config.yaml"
cfg_path.write_text('existing_key: "keep"\n', encoding="utf-8")
os.environ["OPEN_SECOND_BRAIN_CONFIG"] = str(cfg_path)
provider = self._provider(FakeBrainBridge())
provider.save_config(
{"vault": "/v", "agent_name": "a", "timezone": "UTC"}, tmp
)
text = cfg_path.read_text(encoding="utf-8")
self.assertIn('vault: "/v"', text)
self.assertIn('agent_name: "a"', text)
self.assertIn('timezone: "UTC"', text)
self.assertIn('existing_key: "keep"', text)
def test_handle_tool_call_rejects_non_allowlisted_tool(self):
bridge = FakeBrainBridge(results={"brain_dream": {"ok": True}})
provider = self._provider(bridge)
provider.initialize("s", hermes_home="/tmp/hh")
with self.assertRaises(BridgeError):
provider.handle_tool_call("brain_dream", {})
self.assertEqual(bridge.calls, []) # never reached the bridge
def test_save_config_refuses_a_value_that_cannot_survive_read_back(self):
# This used to JSON-encode the value and assert it round-tripped
# through the PLUGIN's reader. It did - and `o2b` read the same line
# back as a different path, because the TypeScript parser strips
# quotes literally and unescapes nothing. The two sides now agree by
# refusing the value instead of storing one each side reads
# differently; `tests/python/test_resolver_parity.py` pins the reader
# half of that agreement.
with tempfile.TemporaryDirectory() as tmp:
cfg_path = Path(tmp) / "config.yaml"
os.environ["OPEN_SECOND_BRAIN_CONFIG"] = str(cfg_path)
provider = self._provider(FakeBrainBridge())
win = 'C:\\Users\\me\\My "Special" Vault'
with self.assertRaises(cfg.ConfigValueError):
provider.save_config({"vault": win}, tmp)
self.assertFalse(cfg_path.exists())
def test_save_config_unsets_a_cleared_field(self):
# A wizard that clears a field must be able to unset it. Skipping
# falsy values kept the old value and reported success.
with tempfile.TemporaryDirectory() as tmp:
cfg_path = Path(tmp) / "config.yaml"
cfg_path.write_text('vault: "/v"\nagent_name: "old"\n', encoding="utf-8")
os.environ["OPEN_SECOND_BRAIN_CONFIG"] = str(cfg_path)
provider = self._provider(FakeBrainBridge())
provider.save_config({"agent_name": ""}, tmp)
text = cfg_path.read_text(encoding="utf-8")
self.assertNotIn("agent_name", text)
self.assertIn('vault: "/v"', text)
self.assertEqual(cfg.resolve_agent_name(), cfg.DEFAULT_AGENT)
def test_save_config_leaves_a_key_the_wizard_did_not_send(self):
with tempfile.TemporaryDirectory() as tmp:
cfg_path = Path(tmp) / "config.yaml"
cfg_path.write_text('agent_name: "keep-me"\n', encoding="utf-8")
os.environ["OPEN_SECOND_BRAIN_CONFIG"] = str(cfg_path)
provider = self._provider(FakeBrainBridge())
provider.save_config({"vault": "/v"}, tmp)
self.assertEqual(cfg.resolve_agent_name(), "keep-me")
def test_save_config_refuses_when_the_environment_shadows_the_write(self):
# The exact case that produces a config the operator can read and a
# vault they are not using.
with tempfile.TemporaryDirectory() as tmp:
cfg_path = Path(tmp) / "config.yaml"
os.environ["OPEN_SECOND_BRAIN_CONFIG"] = str(cfg_path)
os.environ["VAULT_DIR"] = "/elsewhere"
provider = self._provider(FakeBrainBridge())
with self.assertRaises(cfg.ConfigEffectError) as caught:
provider.save_config({"vault": "/v"}, tmp)
self.assertIn("VAULT_DIR", str(caught.exception))
# The write itself is not rolled back: the file holds what was asked
# for, and the error explains why it is not in force.
self.assertIn('vault: "/v"', cfg_path.read_text(encoding="utf-8"))
def test_save_config_replaces_the_line_the_reader_honours(self):
# Duplicate keys: the reader takes the last, so the writer must too.
with tempfile.TemporaryDirectory() as tmp:
cfg_path = Path(tmp) / "config.yaml"
cfg_path.write_text('vault: "/first"\nvault: "/second"\n', encoding="utf-8")
os.environ["OPEN_SECOND_BRAIN_CONFIG"] = str(cfg_path)
provider = self._provider(FakeBrainBridge())
provider.save_config({"vault": "/v"}, tmp)
self.assertEqual(cfg.resolve_vault(), "/v")
self.assertEqual(cfg_path.read_text(encoding="utf-8").count("vault:"), 1)
def test_config_schema_and_write_keys_come_from_one_structure(self):
provider = self._provider(FakeBrainBridge())
schema_keys = tuple(field["key"] for field in provider.get_config_schema())
self.assertEqual(schema_keys, provider_module._CONFIG_KEYS)
@staticmethod
def _host_reads_as_configured(schema):
"""The host's readiness rule, transcribed from hermes-agent.
``_memory_provider_is_configured`` -> ``_field_is_set`` ->
``_field_value`` in ``hermes_cli/web_server.py``: the host has no store
of its own for this provider, so the ``data`` it consults is empty and
every value it sees is the schema field's ``default``. Transcribed
rather than imported because hermes-agent is not a dependency of this
repository and CI has no Hermes install.
"""
required = [field for field in schema if field.get("required")]
return all(str(field.get("default", "")) != "" for field in required)
def test_get_config_schema_reports_the_resolved_values_as_defaults(self):
# The host renders a field's `default` as its current value AND keys
# "is this provider configured" on the same value. With no default, a
# provider configured entirely in its own store read as needing setup,
# and the dashboard refused its own save with HTTP 400 forever.
with tempfile.TemporaryDirectory() as tmp:
cfg_path = Path(tmp) / "config.yaml"
cfg_path.write_text(
'vault: "/v"\nagent_name: "a"\ntimezone: "Etc/UTC"\n', encoding="utf-8"
)
os.environ[cfg.CONFIG_PATH_ENV] = str(cfg_path)
schema = self._provider(FakeBrainBridge()).get_config_schema()
defaults = {field["key"]: field["default"] for field in schema}
self.assertEqual(
defaults, {"vault": "/v", "agent_name": "a", "timezone": "Etc/UTC"}
)
self.assertTrue(self._host_reads_as_configured(schema))
def test_get_config_schema_default_is_the_effective_value_not_the_file_line(self):
# Readiness must mean what `o2b mcp` will actually use: the bridge
# resolves through the same chain, so a vault supplied by the
# environment is a configured provider and the file's line is not.
with tempfile.TemporaryDirectory() as tmp:
cfg_path = Path(tmp) / "config.yaml"
cfg_path.write_text('vault: "/from-file"\n', encoding="utf-8")
os.environ[cfg.CONFIG_PATH_ENV] = str(cfg_path)
os.environ[cfg.VAULT_DIR_ENV] = "/from-env"
schema = self._provider(FakeBrainBridge()).get_config_schema()
defaults = {field["key"]: field["default"] for field in schema}
self.assertEqual(defaults["vault"], "/from-env")
def test_get_config_schema_reports_no_default_when_the_config_is_unreadable(self):
# Two ways this could lie, both refused: inventing a value for a file
# nothing could read, and raising - the host catches a failing schema
# call, renders NO fields, and a provider with no required field reads
# as configured. `is_available()` is what names the broken file.
with tempfile.TemporaryDirectory() as tmp:
cfg_dir = Path(tmp) / "config.yaml"
cfg_dir.mkdir()
os.environ[cfg.CONFIG_PATH_ENV] = str(cfg_dir)
schema = self._provider(FakeBrainBridge()).get_config_schema()
self.assertEqual(
tuple(field["key"] for field in schema), provider_module._CONFIG_KEYS
)
self.assertEqual([field["default"] for field in schema], ["", "", ""])
self.assertFalse(self._host_reads_as_configured(schema))
def test_get_status_config_reports_the_native_store_not_the_hermes_block(self):
# `hermes memory status` passes its own `memory.<name>` block, which
# nothing writes for this provider. Printing it verbatim showed an
# empty config block for a fully configured provider - and a stale one
# for anybody who had pasted the values in there by hand.
with tempfile.TemporaryDirectory() as tmp:
cfg_path = Path(tmp) / "config.yaml"
cfg_path.write_text('vault: "/v"\nagent_name: "a"\n', encoding="utf-8")
os.environ[cfg.CONFIG_PATH_ENV] = str(cfg_path)
status = self._provider(FakeBrainBridge()).get_status_config(
{"vault": "/stale"}
)
self.assertEqual(status["config_file"], str(cfg_path))
self.assertEqual(status["vault"], "/v")
self.assertEqual(status["agent_name"], "a")
# An unset optional key is absent, not an empty string that reads as
# a configured-and-blank timezone.
self.assertNotIn("timezone", status)
def test_is_available_refuses_rather_than_reporting_unconfigured(self):
# The reported symptom: a config that cannot be read looked exactly
# like a plugin nobody had set up.
with tempfile.TemporaryDirectory() as tmp:
cfg_dir = Path(tmp) / "config.yaml"
cfg_dir.mkdir()
os.environ["OPEN_SECOND_BRAIN_CONFIG"] = str(cfg_dir)
provider = self._provider(FakeBrainBridge())
with self.assertRaises(cfg.ConfigReadError) as caught:
provider.is_available()
self.assertIn(str(cfg_dir), str(caught.exception))
self.assertIn("chmod u+r", str(caught.exception))
def test_bridge_start_failure_is_named_by_the_next_tool_call(self):
# A provider whose bridge never started used to stay registered and
# answer every call with None, forever, with nothing saying why.
class RefusingBridge(FakeBrainBridge):
def start(self):
raise BridgeError("o2b mcp is not installed")
provider = self._provider(RefusingBridge())
with self.assertLogs("plugins.hermes.provider", level="ERROR"):
provider.initialize("s", hermes_home="/tmp/hh")
with self.assertRaises(BridgeError) as caught:
provider.handle_tool_call("brain_note", {"text": "hi"})
self.assertIn("o2b mcp is not installed", str(caught.exception))
class ProviderStaticSchemaFallbackTests(unittest.TestCase):
"""Hermes builds its tool routing table BEFORE initialize(); the provider
must advertise the curated tool set from the very first
get_tool_schemas() call, not only after the bridge is up."""
def _curated_live_tools(self):
return [
{"name": name, "description": f"live {name}", "inputSchema": {"type": "object"}}
for name in MEMORY_TOOLS
]
def test_get_tool_schemas_before_initialize_returns_curated_set(self):
provider = OpenSecondBrainMemoryProvider(bridge=FakeBrainBridge())
schemas = provider.get_tool_schemas() # no initialize() yet
self.assertEqual({s["name"] for s in schemas}, set(MEMORY_TOOLS))
for schema in schemas:
self.assertTrue(schema["description"])
# static_tool_schemas() remaps inputSchema -> parameters
self.assertEqual(schema["parameters"].get("type"), "object")
def test_get_tool_schemas_after_initialize_keeps_name_set(self):
bridge = FakeBrainBridge(tools=self._curated_live_tools())
provider = OpenSecondBrainMemoryProvider(bridge=bridge)
before = {s["name"] for s in provider.get_tool_schemas()}
provider.initialize("s", hermes_home="/tmp/hh")
after = {s["name"] for s in provider.get_tool_schemas()}
self.assertEqual(before, after)
# Live schemas win once the bridge is up.
self.assertTrue(
all(s["description"].startswith("live ") for s in provider.get_tool_schemas())
)
def test_get_tool_schemas_falls_back_to_static_when_listing_fails(self):
class _ListingFailsBridge(FakeBrainBridge):
def list_tools(self):
raise BridgeError("listing failed")
provider = OpenSecondBrainMemoryProvider(bridge=_ListingFailsBridge())
provider.initialize("s", hermes_home="/tmp/hh")
names = {s["name"] for s in provider.get_tool_schemas()}
self.assertEqual(names, set(MEMORY_TOOLS))
def test_handle_tool_call_before_initialize_still_raises(self):
provider = OpenSecondBrainMemoryProvider(bridge=FakeBrainBridge())
with self.assertRaises(BridgeError):
provider.handle_tool_call("brain_note", {"text": "early"})
def test_hermes_registration_ordering_end_to_end(self):
# Simulate MemoryManager.add_provider(): the routing table is built
# from get_tool_schemas() BEFORE initialize_all() runs.
bridge = FakeBrainBridge(
tools=self._curated_live_tools(),
results={"brain_note": {"ok": True}},
)
provider = OpenSecondBrainMemoryProvider(bridge=bridge)
routing_table = {s["name"]: provider for s in provider.get_tool_schemas()}
self.assertGreaterEqual(len(routing_table), 1) # "registered (N tools)", N >= 1
self.assertIn("brain_note", routing_table)
# initialize_all() runs after registration; the model then calls a tool.
provider.initialize("sess-1", hermes_home="/tmp/hh")
result = routing_table["brain_note"].handle_tool_call("brain_note", {"text": "hi"})
self.assertIsInstance(result, str)
self.assertEqual(json.loads(result), {"ok": True})
self.assertEqual(bridge.calls, [("brain_note", {"text": "hi"})])
@staticmethod
def _fake_bin(home, relative, name):
"""Create an executable stub at ``<home>/<relative>/<name>``."""
directory = Path(home).joinpath(*relative)
directory.mkdir(parents=True, exist_ok=True)
# Windows discovery matches PATHEXT suffixes, not a bare name.
if os.name == "nt" and not os.path.splitext(name)[1]:
name += ".exe"
exe = directory / name
exe.write_text("#!/bin/sh\n")
os.chmod(exe, 0o755)
return exe
@staticmethod
def _sandboxed_scan(home, *dirs):
"""Patches that confine executable discovery to ``home``.
Both the PATH lookup and the fallback scan are pinned: leaving the scan
on its real directory list would let a Bun installed on the machine
running the tests decide the outcome.
"""
return (
patch.dict(os.environ, {"PATH": ""}),
patch.object(Path, "home", return_value=Path(home)),
patch("shutil.which", return_value=None),
patch.object(
provider_module,
"_fallback_exe_dirs",
return_value=tuple(Path(home).joinpath(*d) for d in dirs),
),
)
@unittest.skipIf(os.name == "nt", "o2b bash wrapper is POSIX-only")
def test_resolve_command_uses_user_local_o2b_when_path_is_tiny(self):
# A tiny inherited PATH hides o2b from shutil.which; the fallback scan
# must still find a real user-local o2b. The wrapper is only preferred
# when a Bun exists for it to run, so the sandbox carries one too.
# Hermetic: fake bins under a temp HOME and a scan list confined to it,
# so the assertion never depends on what this machine has installed.
with tempfile.TemporaryDirectory() as home:
fake_o2b = self._fake_bin(home, (".local", "bin"), "o2b")
self._fake_bin(home, (".bun", "bin"), "bun")
with contextlib.ExitStack() as stack:
for ctx in self._sandboxed_scan(home, (".local", "bin"), (".bun", "bin")):
stack.enter_context(ctx)
command = OpenSecondBrainMemoryProvider._resolve_command()
self.assertEqual(command, (str(fake_o2b), "mcp"))
self.assertTrue(Path(command[0]).is_absolute())
@unittest.skipUnless(os.name == "nt", "o2b.cmd launcher is Windows-only")
def test_windows_last_resort_resolves_the_o2b_cmd_launcher(self):
# CreateProcess appends only ``.exe`` to a bare name, so the bare
# ``("o2b", "mcp")`` fallback cannot start ``o2b.cmd`` on Windows.
with tempfile.TemporaryDirectory() as home:
fake_o2b = self._fake_bin(home, (".local", "bin"), "o2b.cmd")
with contextlib.ExitStack() as stack:
for ctx in self._sandboxed_scan(home, (".local", "bin")):
stack.enter_context(ctx)
command = OpenSecondBrainMemoryProvider._resolve_command()
self.assertEqual(command[0].lower(), str(fake_o2b).lower())
self.assertEqual(command[1:], ("mcp",))
@unittest.skipIf(os.name == "nt", "o2b bash wrapper is POSIX-only")
def test_resolve_command_skips_o2b_wrapper_when_no_bun_is_discoverable(self):
# The wrapper is a bash script that exits 127 when its own PATH has no
# bun. Preferring it with no bun anywhere yields a command that can only
# fail, so resolution must fall through to the repo-local branch.
with tempfile.TemporaryDirectory() as home:
self._fake_bin(home, (".local", "bin"), "o2b")
entry = Path("/repo/src/cli/main.ts")
with contextlib.ExitStack() as stack:
for ctx in self._sandboxed_scan(home, (".local", "bin")):
stack.enter_context(ctx)
stack.enter_context(
patch.object(
OpenSecondBrainMemoryProvider, "_repo_root", return_value="/repo"
)
)
stack.enter_context(patch.object(Path, "is_file", return_value=True))
command = OpenSecondBrainMemoryProvider._resolve_command()
# No bun means the bun+entry branch cannot be built either, so the
# last-resort bare command is what is left - never the wrapper.
self.assertEqual(command, ("o2b", "mcp"))
self.assertNotIn(str(entry), command)
def test_resolve_command_uses_bun_entry_when_only_bun_is_discoverable(self):
with tempfile.TemporaryDirectory() as home:
fake_bun = self._fake_bin(home, (".bun", "bin"), "bun")
with contextlib.ExitStack() as stack:
for ctx in self._sandboxed_scan(home, (".bun", "bin")):
stack.enter_context(ctx)
stack.enter_context(
patch.object(
OpenSecondBrainMemoryProvider, "_repo_root", return_value="/repo"
)
)
stack.enter_context(patch.object(Path, "is_file", return_value=True))
command = OpenSecondBrainMemoryProvider._resolve_command()
# ``Path.is_file`` is patched to True, so on Windows the PATHEXT scan
# may settle on another suffix (bun.COM) in the same directory.
self.assertEqual(Path(command[0]).parent, fake_bun.parent)
self.assertEqual(Path(command[0]).stem, "bun")
self.assertEqual(command[1], "run")
self.assertEqual(command[-1], "mcp")
def test_resolve_env_puts_the_discovered_bun_directory_first_on_path(self):
# Issue #173: the o2b wrapper checks `command -v bun` against the PATH
# it inherits. Resolving an absolute bun here is useless unless the
# child can see it too.
with tempfile.TemporaryDirectory() as home:
fake_bun = self._fake_bin(home, (".bun", "bin"), "bun")
with contextlib.ExitStack() as stack:
for ctx in self._sandboxed_scan(home, (".bun", "bin")):
stack.enter_context(ctx)
env = OpenSecondBrainMemoryProvider._resolve_env()
self.assertIsNotNone(env)
self.assertEqual(env["PATH"].split(os.pathsep)[0], str(fake_bun.parent))
def test_resolve_env_inherits_when_path_already_resolves_bun(self):
with patch("shutil.which", return_value="/usr/bin/bun"):
self.assertIsNone(OpenSecondBrainMemoryProvider._resolve_env())
def test_resolve_env_inherits_when_no_bun_exists_anywhere(self):
with tempfile.TemporaryDirectory() as home:
with contextlib.ExitStack() as stack:
for ctx in self._sandboxed_scan(home, (".bun", "bin")):
stack.enter_context(ctx)
self.assertIsNone(OpenSecondBrainMemoryProvider._resolve_env())
def test_find_executable_prefers_which(self):
with patch("shutil.which", return_value="/somewhere/on/path/o2b"):
self.assertEqual(_find_executable("o2b"), "/somewhere/on/path/o2b")
def test_find_executable_returns_none_when_nothing_resolves(self):
with tempfile.TemporaryDirectory() as empty, patch("shutil.which", return_value=None):
self.assertIsNone(_find_executable("o2b", search_dirs=[Path(empty)]))
def test_find_executable_matches_windows_pathext_suffix(self):
# On Windows a bare `bun` never matches on disk; the scan must try the
# PATHEXT suffixes (bun.CMD / bun.EXE). Execute-bit gating is a POSIX
# concept and must be skipped there. Build the Path objects before
# patching os.name, since pathlib picks its flavour at instantiation.
with tempfile.TemporaryDirectory() as bindir:
bindir_path = Path(bindir)
shim = bindir_path / "bun.CMD"
shim.write_text("@echo off\n")
with (
patch("os.name", "nt"),
patch("os.pathsep", ";"),
patch.dict(os.environ, {"PATHEXT": ".COM;.EXE;.BAT;.CMD"}),
patch("shutil.which", return_value=None),
):
resolved = _find_executable("bun", search_dirs=[bindir_path])
self.assertEqual(resolved, str(shim))
def test_find_executable_ignores_a_copy_in_the_current_directory_on_windows(self):
# shutil.which on Windows looks in the current directory before PATH,
# and Hermes runs in the project it was opened in: a bun.cmd that
# project ships must not be the Bun the bridge starts.
with tempfile.TemporaryDirectory() as project, tempfile.TemporaryDirectory() as bindir:
planted = os.path.join(project, "bun.cmd")
real = os.path.join(bindir, "bun.CMD")
for p in (planted, real):
with open(p, "w") as fh:
fh.write("@echo off\n")
with (
patch("os.name", "nt"),
patch("os.pathsep", ";"),
patch("os.getcwd", return_value=project),
patch.dict(os.environ, {"PATHEXT": ".COM;.EXE;.BAT;.CMD", "PATH": bindir}),
patch("shutil.which", return_value=planted),
):
self.assertEqual(_find_executable("bun", search_dirs=[]), real)
# A current directory the user put on PATH on purpose is honoured.
with (
patch("os.name", "nt"),
patch("os.pathsep", ";"),
patch("os.getcwd", return_value=project),
patch.dict(os.environ, {"PATHEXT": ".CMD", "PATH": f"{project};{bindir}"}),
patch("shutil.which", return_value=planted),
):
self.assertEqual(_find_executable("bun", search_dirs=[]), planted)
class CliTests(unittest.TestCase):
_ENV_KEYS = _CONFIG_ENV_KEYS
def setUp(self):
self._saved = {k: os.environ.pop(k, None) for k in self._ENV_KEYS}
def tearDown(self):
for k in self._ENV_KEYS:
os.environ.pop(k, None)
if self._saved[k] is not None:
os.environ[k] = self._saved[k]
def _run(self, argv):
import argparse
import contextlib
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest="cmd")
osb = subparsers.add_parser("open-second-brain")
register_cli(osb)
args = parser.parse_args(["open-second-brain", *argv])
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
rc = args.func(args)
return rc, buf.getvalue()
def test_status_reports_provider_and_availability(self):
os.environ["VAULT_DIR"] = "/tmp/cli-vault"
rc, out = self._run(["status"])
self.assertEqual(rc, 0)
self.assertIn("open-second-brain", out)
self.assertIn("/tmp/cli-vault", out)
def test_status_nonzero_when_unavailable(self):
with tempfile.TemporaryDirectory() as tmp:
os.environ["OPEN_SECOND_BRAIN_CONFIG"] = str(Path(tmp) / "missing.yaml")
rc, _ = self._run(["status"])
self.assertEqual(rc, 1)
def test_config_reports_effective_values(self):
with tempfile.TemporaryDirectory() as tmp:
cfg_path = Path(tmp) / "config.yaml"
cfg_path.write_text('vault: "/v"\nagent_name: "cli-agent"\n', encoding="utf-8")
os.environ["OPEN_SECOND_BRAIN_CONFIG"] = str(cfg_path)
rc, out = self._run(["config"])
self.assertEqual(rc, 0)
self.assertIn("/v", out)
self.assertIn("cli-agent", out)
def test_unreadable_config_is_a_named_line_not_a_traceback(self):
# These two commands are what an operator is asked to run when the
# setup badge is already wrong (GitHub #130). `is_available` refuses
# rather than answering False for an unreadable config, which is right
# for the badge and useless here: a traceback would bury the one line
# naming the remedy. The exit code separates "could not read the
# config" from "read it, and it says not ready", which is exit 1.
if os.name == "nt":
self.skipTest("chmod 0o000 only sets read-only on Windows; the file stays readable")
if os.getuid() == 0:
self.skipTest("root ignores the mode bits this test relies on")
with tempfile.TemporaryDirectory() as tmp:
cfg_path = Path(tmp) / "config.yaml"
cfg_path.write_text('vault: "/v"\n', encoding="utf-8")
cfg_path.chmod(0o000)
os.environ["OPEN_SECOND_BRAIN_CONFIG"] = str(cfg_path)
try:
for verb in ("config", "status"):
with self.subTest(verb=verb):
buf = io.StringIO()
with contextlib.redirect_stderr(buf):
rc, out = self._run([verb])
self.assertEqual(rc, 2)
self.assertIn("error:", buf.getvalue())
self.assertIn(str(cfg_path), buf.getvalue())
# The path this process actually looked at is printed
# even when the file behind it is not readable.
if verb == "config":
self.assertIn(str(cfg_path), out)
finally:
cfg_path.chmod(0o600)
class _RaisingBridge(FakeBrainBridge):
"""Bridge whose tool calls always fail, to prove hooks are exception-safe."""
def call_tool(self, name, args):
raise BridgeError("boom")
class ProviderLifecycleTests(unittest.TestCase):
_ENV_KEYS = _CONFIG_ENV_KEYS
def setUp(self):
self._saved = {k: os.environ.pop(k, None) for k in self._ENV_KEYS}
def tearDown(self):
for k in self._ENV_KEYS:
os.environ.pop(k, None)
if self._saved[k] is not None:
os.environ[k] = self._saved[k]
def _init(self, bridge, **kwargs):
provider = OpenSecondBrainMemoryProvider(bridge=bridge)
provider.initialize("sess-1", **kwargs)
return provider
def test_system_prompt_block_returns_active_content(self):
bridge = FakeBrainBridge(
results={"brain_context": {"structuredContent": {"content": "ACTIVE PREFS"}}}
)
provider = self._init(bridge, hermes_home="/tmp/hh")
self.assertEqual(provider.system_prompt_block(), "ACTIVE PREFS")
def test_prefetch_returns_recall_and_reminder_when_gate_retrieves(self):
os.environ["VAULT_AGENT_NAME"] = "pf-agent"
bridge = FakeBrainBridge(
results={
"brain_recall_gate": {"structuredContent": {"retrieve": True, "reason": "hit"}},
"brain_context_pack": {"content": [{"type": "text", "text": "RECALLED"}]},
}
)
provider = self._init(bridge, hermes_home="/tmp/hh")
out = provider.prefetch("what did we decide", session_id="sess-1")
self.assertIn("RECALLED", out)
self.assertIn("@pf-agent", out)
def test_prefetch_query_reaches_the_pack_lane(self):
# The turn's query rides the curated lane in ranked mode, so the
# guard, the preference pool, the budget and the receipt all still
# apply. Nothing is recalled through raw brain_search.
bridge = FakeBrainBridge(
results={
"brain_recall_gate": {"structuredContent": {"retrieve": True}},
"brain_context_pack": {
"structuredContent": {
"receipt_id": "receipt-ranked",
"items": [{"body": "quote the enterprise tier first"}],
}
},
}
)
provider = self._init(bridge, hermes_home="/tmp/hh")
out = provider.prefetch("which pricing rule applies", session_id="sess-1", turn_id="turn-7")
self.assertIn("quote the enterprise tier first", out)
self.assertNotIn("brain_search", [name for name, _ in bridge.calls])
pack_args = next(a for n, a in bridge.calls if n == "brain_context_pack")
self.assertEqual(pack_args["query"], "which pricing rule applies")
self.assertEqual(pack_args["query_mode"], "ranked")
self.assertEqual(pack_args["turn_id"], "turn-7")
self.assertEqual(pack_args["session_id"], "sess-1")
gate_args = next(a for n, a in bridge.calls if n == "brain_recall_gate")
self.assertEqual(gate_args["turn_id"], "turn-7")
self.assertEqual(gate_args["telemetry_host"], "hermes")
def test_prefetch_bounds_long_queries_and_keeps_the_ends(self):
for query in (
"A" * 2000,
"Start " + "x" * 1981 + " end question?",
"Start " + "x" * 1990 + " end question?",
"Start " + "x" * 4000 + " end question?",
"Start " + "😀" * 4001 + " end question?",
):
with self.subTest(length=len(query)):
bridge = FakeBrainBridge(results={
"brain_recall_gate": {"structuredContent": {"retrieve": True}},
"brain_context_pack": {"content": [{"type": "text", "text": "RECALLED"}]},
})
provider = self._init(bridge, hermes_home="/tmp/hh")
with patch.object(provider_module.logger, "info") as log:
result = provider.prefetch(query, session_id="sess-1")
gate = next(a for n, a in bridge.calls if n == "brain_recall_gate")
pack = next(a for n, a in bridge.calls if n == "brain_context_pack")
self.assertIn("RECALLED", result)
self.assertEqual(gate["prompt"], pack["query"])
self.assertLessEqual(len(pack["query"]), 2000)
self.assertLessEqual(len(gate["prompt"].encode("utf-16-le")) // 2, 4000)
self.assertEqual(next(a for n, a in bridge.calls if n == "skills_attach")["query"], query)
reduced = [c for c in log.call_args_list if "query reduced" in c.args[0]]
if len(query) > 2000:
self.assertEqual(len(pack["query"]), 2000)
self.assertTrue(pack["query"].startswith("Start "))
self.assertTrue(pack["query"].endswith(" end question?"))
self.assertEqual(len(reduced), 1)
else:
self.assertEqual(pack["query"], query)
self.assertEqual(reduced, [])
def test_prefetch_leaves_a_long_blank_turn_unbounded(self):
# Bounding a turn that is blank after trimming would leave only the
# omission marker, a non-blank query that recalls on nothing. The turn
# travels as before: the gate refuses it and the pack gets no query.
query = " \n\t" * 1000
bridge = FakeBrainBridge(results={
"brain_recall_gate": {"structuredContent": {"retrieve": True}},
"brain_context_pack": {"content": [{"type": "text", "text": "RECALLED"}]},
})
provider = self._init(bridge, hermes_home="/tmp/hh")
with patch.object(provider_module.logger, "info") as log:
provider.prefetch(query, session_id="sess-1")
gate = next(a for n, a in bridge.calls if n == "brain_recall_gate")
pack = next(a for n, a in bridge.calls if n == "brain_context_pack")
self.assertEqual(gate["prompt"], query)
self.assertNotIn("query", pack)
self.assertNotIn("query_mode", pack)
self.assertFalse(any("query reduced" in c.args[0] for c in log.call_args_list))
def test_prefetch_forwards_a_non_string_query_without_raising(self):
# A host that hands over None or a non-string still reaches the bridge,
# which answers fail-soft; the bound must not raise first.
for query in (None, 12345):
with self.subTest(query=query):
bridge = FakeBrainBridge(
results={"brain_recall_gate": {"structuredContent": {"retrieve": False}}}
)
provider = self._init(bridge, hermes_home="/tmp/hh")
provider.prefetch(query, session_id="sess-1")
gate = next(a for n, a in bridge.calls if n == "brain_recall_gate")
self.assertIs(gate["prompt"], query)
attach = next(a for n, a in bridge.calls if n == "skills_attach")
self.assertIs(attach["query"], query)
def test_prefetch_keeps_the_server_receipt_as_sample_id(self):
# The sample id an agent later posts an outcome against must be the
# id the server wrote a receipt under, never a locally hashed
# string: an id with no receipt behind it resolves to
# unresolved/sample_absent forever.
bridge = FakeBrainBridge(
results={
"brain_recall_gate": {"structuredContent": {"retrieve": True}},
"brain_context_pack": {
"structuredContent": {
"receipt_id": "receipt-server-issued",
"items": [{"body": "keep RRF"}],
}
},
}
)
provider = self._init(bridge, hermes_home="/tmp/hh")
out = provider.prefetch("what did we decide", session_id="sess-1")
metadata = json.loads(out.split("[O2B context-pack metadata] ", 1)[1].split("\n", 1)[0])
self.assertEqual(metadata["sample_id"], "receipt-server-issued")
self.assertNotIn("hermes-search-", out)
def test_prefetch_surfaces_a_pack_warning_instead_of_swallowing_it(self):
# An injected memory that is the subject of an unresolved tension is
# a degraded recall. The pack names it; the provider must not drop
# the name on the floor.
bridge = FakeBrainBridge(
results={
"brain_recall_gate": {"structuredContent": {"retrieve": True}},
"brain_context_pack": {
"structuredContent": {
"receipt_id": "receipt-warned",
"items": [{"body": "always use tabs"}],
"warnings": ["tension t-123 is unresolved for pref-tabs"],
}
},
}
)
provider = self._init(bridge, hermes_home="/tmp/hh")
with self.assertLogs("plugins.hermes.provider", level="WARNING") as logs:
provider.prefetch("indentation", session_id="sess-1")
self.assertTrue(
any("tension t-123 is unresolved" in line for line in logs.output), logs.output
)
def test_prefetch_has_one_recall_lane_and_names_an_empty_one(self):
# There is no second lane to fall back to, and an empty pack on a
# gated turn says so rather than passing for a healthy injection.
bridge = FakeBrainBridge(
results={
"brain_recall_gate": {"structuredContent": {"retrieve": True}},
"brain_context_pack": {"structuredContent": {"items": []}},
}
)
provider = self._init(bridge, hermes_home="/tmp/hh")
with self.assertLogs("plugins.hermes.provider", level="INFO") as logs:
out = provider.prefetch("what did we decide", session_id="sess-1")
self.assertNotIn("brain_search", [name for name, _ in bridge.calls])
self.assertNotIn("[O2B context-pack metadata]", out)
self.assertTrue(
any("brain_context_pack" in line for line in logs.output), logs.output
)
def test_prefetch_budget_holds_for_cyrillic_and_cjk(self):
# The budget is a TOKEN budget the server enforces, not a character
# budget guessed in Python at four bytes per token - a ratio that is
# wrong by 2x to 4x on Cyrillic and CJK. Nothing is cut locally, and
# the declared budget travels with the request.
for script, body in (
("cyrillic", "\u043f\u0440\u0430\u0432\u0438\u043b\u043e " * 800),
("cjk", "\u5b9a\u4ef7\u89c4\u5219" * 1200),
):
with self.subTest(script=script):
bridge = FakeBrainBridge(
results={
"brain_recall_gate": {"structuredContent": {"retrieve": True}},
"brain_context_pack": {
"structuredContent": {
"receipt_id": "receipt-" + script,
"items": [{"body": body}],
}
},
}
)
provider = self._init(bridge, hermes_home="/tmp/hh")
out = provider.prefetch("q", session_id="sess-1")
self.assertIn(body, out)
pack_args = next(a for n, a in bridge.calls if n == "brain_context_pack")
self.assertEqual(pack_args["max_tokens"], 1024)
def test_prefetch_keeps_a_plain_note_body_intact(self):
# Regression for the deleted `_recall_body`: it scanned every line of
# a result for one beginning `principle:` and returned that value
# alone, so an ordinary note carrying such a line in its BODY was
# reduced to it and the rest was silently deleted.
body = (
"principle: never ship on friday\n"
"We tried it twice and both rollbacks landed on a weekend."
)
bridge = FakeBrainBridge(
results={
"brain_recall_gate": {"structuredContent": {"retrieve": True}},
"brain_context_pack": {
"structuredContent": {"receipt_id": "receipt-plain", "items": [{"body": body}]}
},
}
)
provider = self._init(bridge, hermes_home="/tmp/hh")
out = provider.prefetch("deployments", session_id="sess-1")
self.assertIn("We tried it twice and both rollbacks landed on a weekend.", out)
def test_outcome_list_is_not_silently_host_filtered(self):
# `host` is a READ filter for list/summary, so defaulting it there
# would narrow an agent's query to hermes rows without saying so.
# The correlation defaults belong to `post` alone.
bridge = FakeBrainBridge(
results={"brain_context_pack_outcome": {"structuredContent": {"rows": []}}}
)
provider = self._init(bridge, hermes_home="/tmp/hh")
provider.handle_tool_call("brain_context_pack_outcome", {"operation": "list"})
provider.handle_tool_call("brain_context_pack_outcome", {"operation": "summary"})
provider.handle_tool_call(
"brain_context_pack_outcome",
{"operation": "post", "sample_id": "s", "first_pass_success": True},
)
reads = [
a
for n, a in bridge.calls
if n == "brain_context_pack_outcome" and a["operation"] in ("list", "summary")
]
self.assertEqual(len(reads), 2)
for args in reads:
self.assertNotIn("host", args)
self.assertNotIn("session_id", args)
posted = next(
a
for n, a in bridge.calls
if n == "brain_context_pack_outcome" and a["operation"] == "post"
)
self.assertEqual(posted["host"], "hermes")
self.assertEqual(posted["session_id"], "sess-1")
def test_prefetch_exposes_receipt_and_agent_posts_structured_outcome(self):
bridge = FakeBrainBridge(
results={
"brain_recall_gate": {"structuredContent": {"retrieve": True}},
"brain_context_pack": {
"structuredContent": {
"receipt_id": "receipt-1",
"items": [{"title": "decision", "body": "keep RRF"}],
}
},
"brain_context_pack_outcome": {"structuredContent": {"recorded": True}},
}
)
with tempfile.TemporaryDirectory() as hermes_home:
provider = self._init(bridge, hermes_home=hermes_home)
out = provider.prefetch("what did we decide", session_id="sess-1")
provider.handle_tool_call(
"brain_context_pack_outcome",
{
"operation": "post",
"sample_id": "receipt-1",
"first_pass_success": False,
"repair_required": True,
"host": "hermes",
"session_id": "sess-1",
},
)
self.assertIn('"sample_id": "receipt-1"', out)
# Names the lane under test: an unregistered fake tool answers `{}`,
# so a pin that only asserts on the OUTPUT can keep passing while the
# provider quietly recalls through something else.
self.assertEqual(
[n for n, _ in bridge.calls if n in ("brain_context_pack", "brain_search")],
["brain_context_pack"],
)
self.assertIn("[O2B context-pack metadata] ", out)
pack_args = next(a for n, a in bridge.calls if n == "brain_context_pack")
self.assertEqual(pack_args["query_mode"], "ranked")
self.assertIs(pack_args["receipt"], True)
self.assertEqual(pack_args["receipt_host"], "hermes")
self.assertIs(pack_args["telemetry"], True)
self.assertEqual(pack_args["telemetry_host"], "hermes")
self.assertEqual(pack_args["session_id"], "sess-1")
outcome_args = next(a for n, a in bridge.calls if n == "brain_context_pack_outcome")
self.assertEqual(outcome_args["operation"], "post")
self.assertEqual(outcome_args["sample_id"], "receipt-1")
self.assertIs(outcome_args["first_pass_success"], False)
self.assertIs(outcome_args["repair_required"], True)
self.assertEqual(outcome_args["session_id"], "sess-1")
def test_prefetch_leaves_neutral_outcome_unknown(self):
bridge = FakeBrainBridge(
results={
"brain_recall_gate": {"structuredContent": {"retrieve": True}},
"brain_context_pack": {
"structuredContent": {
"receipt_id": "receipt-neutral",
"items": [{"title": "decision", "body": "keep RRF"}],
}
},
}
)
provider = self._init(bridge, hermes_home="/tmp/hh")
provider.prefetch("what did we decide", session_id="sess-1")
provider.prefetch("tell me something else", session_id="sess-1")
# Both turns recalled through the shipped lane, and neither posted.
self.assertEqual(
[n for n, _ in bridge.calls if n in ("brain_context_pack", "brain_search")],
["brain_context_pack", "brain_context_pack"],
)
self.assertEqual(
[name for name, _ in bridge.calls if name == "brain_context_pack_outcome"], []
)
def test_prefetch_never_infers_outcome_from_raw_turn_text(self):
gate_calls = 0
def gate(_args):
nonlocal gate_calls
gate_calls += 1
return {"structuredContent": {"retrieve": gate_calls == 1}}
bridge = FakeBrainBridge(
results={
"brain_recall_gate": gate,
"brain_context_pack": {
"structuredContent": {
"receipt_id": "receipt-unknown",
"items": [{"title": "decision", "body": "keep RRF"}],
}
},
}
)
with tempfile.TemporaryDirectory() as hermes_home:
provider = self._init(bridge, hermes_home=hermes_home)
provider.prefetch("what did we decide", session_id="sess-1")
provider.prefetch("tell me something else", session_id="sess-1")
provider.prefetch("我之前说过,不对", session_id="sess-1")
self.assertEqual(gate_calls, 3)
# The one gated turn ran on the context-pack lane, and no search lane
# exists to absorb the multilingual turns instead.
self.assertEqual(
[n for n, _ in bridge.calls if n in ("brain_context_pack", "brain_search")],
["brain_context_pack"],
)
self.assertEqual(
[name for name, _ in bridge.calls if name == "brain_context_pack_outcome"], []
)
def test_prefetch_uses_structured_items_bodies_and_skips_preview_envelope(self):
# Regression: when brain_context_pack returns both structuredContent
# items[*].body AND a content[0].text envelope carrying the
# preview-truncation marker (preview_truncated + artifact_id +
# bytes_preview), prefetch must assemble recall from the structured
# bodies — the envelope is a transport artefact, not recall text.
os.environ["VAULT_AGENT_NAME"] = "pf-agent"
preview_text = json.dumps(
{
"preview_truncated": True,
"artifact_id": "art-deadbeef",
"full_chars": 44261,
"bytes_preview": "...truncated...",
}
)
bridge = FakeBrainBridge(
results={
"brain_recall_gate": {"structuredContent": {"retrieve": True, "reason": "hit"}},
"brain_context_pack": {
"structuredContent": {
"items": [
{"title": "note-a", "body": "BODY ALPHA from item A"},
{"title": "note-b", "body": "BODY BETA from item B"},
]
},
"content": [{"type": "text", "text": preview_text}],
},
}
)
provider = self._init(bridge, hermes_home="/tmp/hh")
out = provider.prefetch("any query", session_id="sess-1")
# Both structured bodies must reach the prefetch output.
self.assertIn("BODY ALPHA from item A", out)
self.assertIn("BODY BETA from item B", out)
# The MCP preview envelope must NOT leak into the prompt.
self.assertNotIn("preview_truncated", out)
self.assertNotIn("artifact_id", out)
self.assertNotIn("bytes_preview", out)
self.assertNotIn("art-deadbeef", out)
def test_prefetch_drops_an_empty_structured_pack_instead_of_its_json(self):
# A server that answered with an `items` key has spoken the structured
# contract; an empty pack means nothing to recall. Falling back to the
# text channel there would inject the raw pack JSON - local vault path
# included - into the prompt.
os.environ["VAULT_AGENT_NAME"] = "pf-agent"
raw_pack = json.dumps({"items": [], "vault": "/home/agent/private-vault"})
bridge = FakeBrainBridge(
results={
"brain_recall_gate": {"structuredContent": {"retrieve": True, "reason": "hit"}},
"brain_context_pack": {
"structuredContent": {"items": []},
"content": [{"type": "text", "text": raw_pack}],
},
}
)
provider = self._init(bridge, hermes_home="/tmp/hh")
out = provider.prefetch("any query", session_id="sess-1")
self.assertNotIn("private-vault", out)
self.assertNotIn("items", out)
self.assertIn("@pf-agent", out) # the identity reminder still lands
def test_prefetch_drops_a_pack_whose_item_bodies_are_all_blank(self):
os.environ["VAULT_AGENT_NAME"] = "pf-agent"
raw_pack = json.dumps({"vault": "/home/agent/private-vault"})
bridge = FakeBrainBridge(
results={
"brain_recall_gate": {"structuredContent": {"retrieve": True, "reason": "hit"}},
"brain_context_pack": {
"structuredContent": {
"items": [{"title": "a", "body": " "}, {"title": "b", "body": ""}]
},
"content": [{"type": "text", "text": raw_pack}],
},
}
)
provider = self._init(bridge, hermes_home="/tmp/hh")
out = provider.prefetch("any query", session_id="sess-1")
self.assertNotIn("private-vault", out)
def test_prefetch_falls_back_to_text_when_the_server_omits_items(self):
# A genuinely legacy server exposes no `items` key at all; its text
# payload is still the only recall it can offer.
os.environ["VAULT_AGENT_NAME"] = "pf-agent"
bridge = FakeBrainBridge(
results={
"brain_recall_gate": {"structuredContent": {"retrieve": True, "reason": "hit"}},
"brain_context_pack": {
"structuredContent": {"generated_at": "2026-08-22"},
"content": [{"type": "text", "text": "LEGACY RECALL TEXT"}],
},
}
)
provider = self._init(bridge, hermes_home="/tmp/hh")
out = provider.prefetch("any query", session_id="sess-1")
self.assertIn("LEGACY RECALL TEXT", out)
def test_prefetch_appends_skills_attach_block_when_enabled(self):
os.environ["VAULT_AGENT_NAME"] = "pf-agent"
bridge = FakeBrainBridge(
results={
"brain_recall_gate": {"structuredContent": {"retrieve": False}},
"skills_attach": {
"structuredContent": {
"enabled": True,
"block": "## Relevant skills\n\n- embeddings-setup - configure providers",
"skills": [{"name": "embeddings-setup"}],
}
},
}
)
provider = self._init(bridge, hermes_home="/tmp/hh")
out = provider.prefetch("configure embeddings", session_id="sess-1")
self.assertIn("## Relevant skills", out)
self.assertIn("embeddings-setup", out)
def test_prefetch_unchanged_when_skills_attach_disabled_or_missing(self):
os.environ["VAULT_AGENT_NAME"] = "pf-agent"
bridge = FakeBrainBridge(
results={
"brain_recall_gate": {"structuredContent": {"retrieve": False}},
"skills_attach": {"structuredContent": {"enabled": False, "block": ""}},
}
)
provider = self._init(bridge, hermes_home="/tmp/hh")
out = provider.prefetch("hello", session_id="sess-1")
self.assertNotIn("Relevant skills", out)
self.assertIn("@pf-agent", out)
def test_prefetch_reminder_only_when_gate_declines(self):
os.environ["VAULT_AGENT_NAME"] = "pf-agent"
bridge = FakeBrainBridge(
results={"brain_recall_gate": {"structuredContent": {"retrieve": False}}}
)
provider = self._init(bridge, hermes_home="/tmp/hh")
out = provider.prefetch("hello", session_id="sess-1")
self.assertIn("@pf-agent", out)
self.assertNotIn("RECALLED", out)
called = [name for name, _ in bridge.calls]
self.assertNotIn("brain_context_pack", called)
def test_prefetch_empty_when_no_identity_and_no_recall(self):
with tempfile.TemporaryDirectory() as tmp:
os.environ["OPEN_SECOND_BRAIN_CONFIG"] = str(Path(tmp) / "missing.yaml")
bridge = FakeBrainBridge(
results={"brain_recall_gate": {"structuredContent": {"retrieve": False}}}
)
provider = self._init(bridge, hermes_home="/tmp/hh")
self.assertEqual(provider.prefetch("hi"), "")
def test_sync_turn_buffers_and_pre_compress_flushes_through_extract(self):
bridge = FakeBrainBridge(results={"brain_pre_compact_extract": {"structuredContent": {}}})
provider = self._init(bridge, hermes_home="/tmp/hh")
provider.sync_turn("u1", "a1", session_id="sess-1")
provider.sync_turn("u2", "a2", session_id="sess-1")
provider._drain_captures()
provider.on_pre_compress([])
extract_calls = [a for n, a in bridge.calls if n == "brain_pre_compact_extract"]
self.assertEqual(len(extract_calls), 1)
self.assertIn("u1", extract_calls[0]["text"])
self.assertIn("a2", extract_calls[0]["text"])
self.assertEqual(extract_calls[0]["turn_start"], "0")
self.assertEqual(extract_calls[0]["turn_end"], "2")
# Buffer cleared: a second flush makes no further extract call.
provider.on_session_end([])
self.assertEqual(
len([1 for n, _ in bridge.calls if n == "brain_pre_compact_extract"]), 1
)
def test_on_session_end_clean_close_omits_interrupted_flag(self):
bridge = FakeBrainBridge(results={"brain_pre_compact_extract": {"structuredContent": {}}})
provider = self._init(bridge, hermes_home="/tmp/hh")
provider.sync_turn("u1", "a1", session_id="sess-1")
provider._drain_captures()
provider.on_session_end([])
extract_calls = [a for n, a in bridge.calls if n == "brain_pre_compact_extract"]
self.assertEqual(len(extract_calls), 1)
# A clean close is byte-identical: no interrupted field on the payload.
self.assertNotIn("interrupted", extract_calls[0])
def test_on_session_end_surfaces_interrupted_onto_flush_payload(self):
bridge = FakeBrainBridge(results={"brain_pre_compact_extract": {"structuredContent": {}}})
provider = self._init(bridge, hermes_home="/tmp/hh")
provider.sync_turn("u1", "a1", session_id="sess-1")
provider._drain_captures()
provider.on_session_end([], interrupted=True)
extract_calls = [a for n, a in bridge.calls if n == "brain_pre_compact_extract"]
self.assertEqual(len(extract_calls), 1)
# The interrupted close is recorded honestly on the flushed segment.
self.assertIs(extract_calls[0].get("interrupted"), True)
def test_on_session_end_drains_and_flushes_the_exit_path(self):
# Regression for Hermes #49315: the god-file Phase 4 refactor bound the
# atexit _active_agent_ref to the mixin module instead of cli.py, so
# on_session_end never fired on CLI /exit and end-of-session capture was
# silently lost. The hook is native again; this guards the path /exit now
# drives by calling on_session_end WITHOUT a prior manual _drain_captures()
# — the hook must self-drain the in-flight sync_turn thread and flush.
bridge = FakeBrainBridge(results={"brain_pre_compact_extract": {"structuredContent": {}}})
provider = self._init(bridge, hermes_home="/tmp/hh")
provider.sync_turn("u1", "a1", session_id="sess-1")
# No _drain_captures() here: end-of-session capture must work end to end.
provider.on_session_end([])
extract_calls = [a for n, a in bridge.calls if n == "brain_pre_compact_extract"]
self.assertEqual(len(extract_calls), 1)
self.assertIn("u1", extract_calls[0]["text"])
self.assertIn("a1", extract_calls[0]["text"])
# The capture threads were joined: drain ran inside the hook.
self.assertEqual(provider._sync_threads, [])
def test_on_memory_write_forwards_to_host_bridge_tool(self):
bridge = FakeBrainBridge(
results={"brain_memory_bridge": {"structuredContent": {"recorded": True}}}
)
provider = self._init(bridge, hermes_home="/tmp/hh")
provider.on_memory_write(
"add", "user", "remember the vault path", metadata={"session_id": "s1"}
)
bridge_calls = [a for n, a in bridge.calls if n == "brain_memory_bridge"]
self.assertEqual(len(bridge_calls), 1)
self.assertEqual(bridge_calls[0]["action"], "add")
self.assertEqual(bridge_calls[0]["target"], "user")
self.assertEqual(bridge_calls[0]["content"], "remember the vault path")
self.assertEqual(bridge_calls[0]["metadata"], {"session_id": "s1"})
# The deprecated brain_note mirror path is gone.
self.assertEqual([n for n, _ in bridge.calls if n == "brain_note"], [])
def test_on_memory_write_omits_empty_metadata(self):
bridge = FakeBrainBridge(results={"brain_memory_bridge": {"structuredContent": {}}})
provider = self._init(bridge, hermes_home="/tmp/hh")
provider.on_memory_write("replace", "memory", "an observation")
args = next(a for n, a in bridge.calls if n == "brain_memory_bridge")
self.assertNotIn("metadata", args)
def test_on_memory_write_is_noop_without_a_bridge(self):
# No host invocation path: a provider with no started bridge writes nothing.
provider = OpenSecondBrainMemoryProvider(bridge=None)
provider.on_memory_write("add", "user", "x") # must not raise
def test_memory_bridge_tool_is_not_agent_facing(self):
# The host bridge tool is advertised on the server but deliberately kept
# out of the curated agent surface: the Hermes agent must not see or be
# able to invoke it directly — only the on_memory_write hook calls it.
self.assertNotIn("brain_memory_bridge", MEMORY_TOOLS)
bridge = FakeBrainBridge()
provider = self._init(bridge, hermes_home="/tmp/hh")
with self.assertRaises(BridgeError):
provider.handle_tool_call("brain_memory_bridge", {"action": "add"})
def test_shutdown_stops_bridge(self):
bridge = FakeBrainBridge()
provider = self._init(bridge, hermes_home="/tmp/hh")
provider.shutdown()
self.assertTrue(bridge.stopped)
def test_hooks_are_exception_safe(self):
os.environ["VAULT_AGENT_NAME"] = "safe-agent"
provider = self._init(_RaisingBridge(), hermes_home="/tmp/hh")
# None of these may raise even though every bridge call fails.
self.assertEqual(provider.system_prompt_block(), "")
self.assertIn("@safe-agent", provider.prefetch("q"))
provider.sync_turn("u", "a")
provider._drain_captures()
provider.on_pre_compress([])
provider.on_session_end([])
provider.on_memory_write("add", "user", "x")
provider.shutdown()
class SharedProviderBridgeTests(unittest.TestCase):
def tearDown(self):
_reset_shared_bridges_for_tests()
def test_provider_instances_share_one_gateway_bridge(self):
shared = FakeBrainBridge()
with patch("plugins.hermes.provider.McpBrainBridge", return_value=shared) as factory:
with patch("plugins.hermes.provider.config.resolve_vault", return_value="/vault"):
with patch.object(
OpenSecondBrainMemoryProvider,
"_repo_root",
return_value="/repo",
):
with patch.object(
OpenSecondBrainMemoryProvider,
"_resolve_command",
return_value=("bun", "run", "main.ts", "mcp"),
):
first = OpenSecondBrainMemoryProvider()
second = OpenSecondBrainMemoryProvider()
first.initialize("session-1", hermes_home="/hh")
second.initialize("session-2", hermes_home="/hh")
self.assertEqual(factory.call_count, 1)
self.assertTrue(shared.started)
first.shutdown()
second.shutdown()
self.assertFalse(shared.stopped)
_reset_shared_bridges_for_tests()
self.assertTrue(shared.stopped)
class InPlaceCompactionLifecycleTests(unittest.TestCase):
"""Regression guards for Hermes PR #52658 (compression.in_place default
False->True). Compaction now keeps ONE durable session id instead of
rotating it, so the provider must flush exactly once per boundary that has
buffered turns, clear its buffer between flushes (no double-flush /
clobber), and make no assumption that the session id rotates.
"""
_ENV_KEYS = _CONFIG_ENV_KEYS
def setUp(self):
self._saved = {k: os.environ.pop(k, None) for k in self._ENV_KEYS}
def tearDown(self):
for k in self._ENV_KEYS:
os.environ.pop(k, None)
if self._saved[k] is not None:
os.environ[k] = self._saved[k]
def _init(self, bridge, session_id):
provider = OpenSecondBrainMemoryProvider(bridge=bridge)
provider.initialize(session_id, hermes_home="/tmp/hh")
return provider
@staticmethod
def _extract_calls(bridge):
return [a for n, a in bridge.calls if n == "brain_pre_compact_extract"]
def test_repeated_in_place_compaction_flushes_each_boundary_once_with_stable_session_id(self):
bridge = FakeBrainBridge(results={"brain_pre_compact_extract": {"structuredContent": {}}})
provider = self._init(bridge, "sess-stable")
# Buffer a turn, then fire boundary #1 (in-place compaction).
provider.sync_turn("u1", "a1", session_id="sess-stable")
provider._drain_captures()
provider.on_pre_compress([]) # boundary #1: flushes the buffered turn
# Boundary #2 uses the SAME (non-rotating) session id but no new turn
# was buffered; the buffer was cleared by #1, so it must NOT re-flush.
provider.on_pre_compress([]) # boundary #2: zero extract calls
# A final session end (still the same stable id) also adds nothing.
provider.on_session_end([]) # zero extract calls
extract_calls = self._extract_calls(bridge)
self.assertEqual(len(extract_calls), 1)
# The single flush carried the stable session id, never a rotated one.
self.assertEqual(extract_calls[0]["session_id"], "sess-stable")
self.assertIn("u1", extract_calls[0]["text"])
self.assertIn("a1", extract_calls[0]["text"])
# Now buffer NEW turns between boundary #1 and a later boundary and
# assert the next boundary flushes only the new turns — no re-flush of
# #1's content, proving no duplicate/clobbered writes accumulate under
# a stable id.
provider.sync_turn("u2", "a2", session_id="sess-stable")
provider._drain_captures()
provider.on_pre_compress([]) # boundary #3: flushes only u2/a2
extract_calls = self._extract_calls(bridge)
self.assertEqual(len(extract_calls), 2)
second = extract_calls[1]
self.assertEqual(second["session_id"], "sess-stable")
self.assertIn("u2", second["text"])
self.assertNotIn("u1", second["text"])
self.assertNotIn("a1", second["text"])
def test_stable_session_id_does_not_assume_rotation(self):
# Decision guard: the provider makes NO assumption that session_id
# changes across compaction. Passing the same id to repeated sync_turn
# + on_pre_compress produces independent, dedup-safe flushes — each
# carries only the turns buffered since the previous boundary, keyed by
# the one stable id (the TS core dedupes by content hash downstream).
bridge = FakeBrainBridge(results={"brain_pre_compact_extract": {"structuredContent": {}}})
provider = self._init(bridge, "sess-stable")
for tag in ("t1", "t2", "t3"):
provider.sync_turn(f"u-{tag}", f"a-{tag}", session_id="sess-stable")
provider._drain_captures()
provider.on_pre_compress([])
extract_calls = self._extract_calls(bridge)
self.assertEqual(len(extract_calls), 3)
# Every flush used the one stable id; none assumed a rotated/new id.
self.assertEqual({c["session_id"] for c in extract_calls}, {"sess-stable"})
# Each flush is independent — it carries only its own turn, so repeated
# in-place compaction under one id cannot clobber a prior boundary.
self.assertIn("u-t1", extract_calls[0]["text"])
self.assertNotIn("u-t2", extract_calls[0]["text"])
self.assertIn("u-t3", extract_calls[2]["text"])
self.assertNotIn("u-t1", extract_calls[2]["text"])
# turn_end reflects the per-boundary buffer size (1), not a cumulative
# count — no unbounded growth across in-place compaction cycles.
self.assertTrue(all(c["turn_end"] == "1" for c in extract_calls))
class _ScriptedReader:
"""Readline source that yields pre-built JSON-RPC frames in order."""
def __init__(self, frames):
self._lines = [(json.dumps(f) + "\n").encode("utf-8") for f in frames]
self._i = 0
def readline(self):
if self._i >= len(self._lines):
return b""
line = self._lines[self._i]
self._i += 1
return line
class _ScriptedStderr:
"""Stderr stand-in that survives the close() the bridge performs.
A real pipe is closed by ``stop()`` while the drain thread may still be
reading it; a closed ``BytesIO`` would make the excerpt race with teardown.
This one keeps serving its scripted payload and then reports EOF, so the
drain thread always terminates on its own and the assertion is about the
buffer rather than about thread timing.
Reads are served in whatever size is asked for, like the raw pipe the
bridge gets from ``Popen(bufsize=0)`` - never rounded up to a line, since
the drain must not depend on the child having sent one.
"""
def __init__(self, lines):
self._payload = b"".join(
line.encode("utf-8") if isinstance(line, str) else line for line in lines
)
self._i = 0
self.closed = False
self.max_read_size = 0
def read(self, size=-1):
if self._i >= len(self._payload):
return b""
end = len(self._payload) if size is None or size < 0 else self._i + size
chunk = self._payload[self._i : end]
self._i = end
self.max_read_size = max(self.max_read_size, len(chunk))
return chunk
def close(self):
self.closed = True
class _FakeProcess:
"""Minimal Popen stand-in: captures stdin writes, scripts stdout reads."""
def __init__(self, responses, stderr_lines=None):
self.stdin = io.BytesIO()
self.stdout = _ScriptedReader(responses)
self.stderr = _ScriptedStderr(stderr_lines or [])
self.pid = 4242
self.terminated = False
self._returncode = None
def poll(self):
return self._returncode
def terminate(self):
self.terminated = True
self._returncode = 0
def wait(self, timeout=None):
self._returncode = 0
return 0
def kill(self):
self._returncode = -9
class JsonRpcStdioClientTests(unittest.TestCase):
def test_request_correlates_by_id_and_skips_noise(self):
writer = io.BytesIO()
# A notification (no id) and a mismatched id must be skipped before
# the matching response is returned.
reader = _ScriptedReader(
[
{"jsonrpc": "2.0", "method": "notifications/progress"},
{"jsonrpc": "2.0", "id": 999, "result": {"stale": True}},
{"jsonrpc": "2.0", "id": 1, "result": {"ok": True}},
]
)
client = JsonRpcStdioClient(writer, reader)
result = client.request("ping", {})
self.assertEqual(result, {"ok": True})
sent = json.loads(writer.getvalue().strip().splitlines()[0])
self.assertEqual(sent["method"], "ping")
self.assertEqual(sent["id"], 1)
def test_error_response_raises(self):
reader = _ScriptedReader(
[{"jsonrpc": "2.0", "id": 1, "error": {"code": -32601, "message": "nope"}}]
)
client = JsonRpcStdioClient(io.BytesIO(), reader)
with self.assertRaises(BridgeError):
client.request("missing", {})
def test_error_response_exposes_the_stable_code(self):
# Every JSON-RPC error carries error.data.code; the bridge hands it
# over as an attribute so Hermes need not parse the rendered dict.
error = {"code": -32601, "message": "nope", "data": {"code": "method_not_found"}}
reader = _ScriptedReader([{"jsonrpc": "2.0", "id": 1, "error": error}])
client = JsonRpcStdioClient(io.BytesIO(), reader)
with self.assertRaises(BridgeError) as caught:
client.request("missing", {})
self.assertEqual(caught.exception.code, "method_not_found")
self.assertEqual(str(caught.exception), str(error))
def test_error_response_without_a_string_code_has_none(self):
for error in (
{"code": -32601, "message": "nope"},
{"code": -32601, "message": "nope", "data": ["x"]},
{"code": -32601, "message": "nope", "data": {"code": 42}},
):
with self.subTest(error=error):
reader = _ScriptedReader([{"jsonrpc": "2.0", "id": 1, "error": error}])
client = JsonRpcStdioClient(io.BytesIO(), reader)
with self.assertRaises(BridgeError) as caught:
client.request("missing", {})
self.assertIsNone(caught.exception.code)
def test_eof_raises(self):
client = JsonRpcStdioClient(io.BytesIO(), _ScriptedReader([]))
with self.assertRaises(BridgeError):
client.request("ping", {})
class McpBrainBridgeTests(unittest.TestCase):
def _handshake_frames(self, extra=None):
frames = [
{"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2025-06-18"}},
{
"jsonrpc": "2.0",
"id": 2,
"result": {"tools": [{"name": "brain_query"}, {"name": "brain_note"}]},
},
]
if extra:
frames.extend(extra)
return frames
def test_start_runs_handshake_and_lists_tools(self):
proc = _FakeProcess(self._handshake_frames())
bridge = McpBrainBridge(vault="/v", spawn=lambda argv: proc)
bridge.start()
names = [t["name"] for t in bridge.list_tools()]
self.assertEqual(names, ["brain_query", "brain_note"])
# initialize then tools/list were written; argv carried the vault.
methods = [json.loads(line)["method"] for line in proc.stdin.getvalue().splitlines()]
self.assertEqual(methods[0], "initialize")
self.assertIn("notifications/initialized", methods)
self.assertIn("tools/list", methods)
def test_call_tool_forwards_name_and_arguments(self):
extra = [{"jsonrpc": "2.0", "id": 3, "result": {"content": "ok"}}]
proc = _FakeProcess(self._handshake_frames(extra))
bridge = McpBrainBridge(vault="/v", spawn=lambda argv: proc)
bridge.start()
result = bridge.call_tool("brain_query", {"q": "x"})
self.assertEqual(result, {"content": "ok"})
last = json.loads(proc.stdin.getvalue().splitlines()[-1])
self.assertEqual(last["method"], "tools/call")
self.assertEqual(last["params"], {"name": "brain_query", "arguments": {"q": "x"}})
def test_argv_includes_vault(self):
captured = {}
def spy(argv):
captured["argv"] = argv
return _FakeProcess(self._handshake_frames())
McpBrainBridge(vault="/my/vault", spawn=spy).start()
self.assertIn("--vault", captured["argv"])
self.assertIn("/my/vault", captured["argv"])
def test_argv_includes_repo_root(self):
captured = {}
def spy(argv):
captured["argv"] = argv
return _FakeProcess(self._handshake_frames())
McpBrainBridge(vault="/v", repo_root="/my/repo", spawn=spy).start()
self.assertIn("--repo", captured["argv"])
self.assertIn("/my/repo", captured["argv"])
def test_argv_omits_repo_when_unset(self):
captured = {}
def spy(argv):
captured["argv"] = argv
return _FakeProcess(self._handshake_frames())
McpBrainBridge(vault="/v", spawn=spy).start()
self.assertNotIn("--repo", captured["argv"])
def test_argv_ends_with_the_hermes_harness(self):
# The server resolves its harness scope from this launch argument
# alone; it never trusts a name the client gives about itself.
cases = (
({"vault": "/v", "repo_root": "/r"}, ["o2b", "mcp", "--vault", "/v", "--repo", "/r"]),
({"vault": "/v"}, ["o2b", "mcp", "--vault", "/v"]),
({"vault": None, "repo_root": "/r"}, ["o2b", "mcp", "--repo", "/r"]),
({"vault": None}, ["o2b", "mcp"]),
)
self.assertEqual(bridge_module.HARNESS_ARGV, ("--harness", "hermes"))
for kwargs, head in cases:
with self.subTest(**kwargs):
captured = {}
def spy(argv):
captured["argv"] = argv
return _FakeProcess(self._handshake_frames())
McpBrainBridge(spawn=spy, **kwargs).start()
self.assertEqual(captured["argv"], [*head, "--harness", "hermes"])
def test_stop_terminates_process(self):
proc = _FakeProcess(self._handshake_frames())
bridge = McpBrainBridge(vault="/v", spawn=lambda argv: proc)
bridge.start()
bridge.stop()
self.assertTrue(proc.terminated)
def _counting_spawn(self, *procs):
it = iter(procs)
state = {"n": 0}
def spawn(argv):
state["n"] += 1
return next(it)
spawn.state = state
return spawn
def test_tool_error_response_propagates_without_restart(self):
# A JSON-RPC error (e.g. invalid arguments) is a server rejection, not
# a dead channel: it must propagate and must not respawn the process.
err = [{"jsonrpc": "2.0", "id": 3, "error": {"code": -32602, "message": "bad args"}}]
spawn = self._counting_spawn(_FakeProcess(self._handshake_frames(err)))
bridge = McpBrainBridge(vault="/v", spawn=spawn)
bridge.start()
with self.assertRaises(BridgeError) as ctx:
bridge.call_tool("brain_query", {})
self.assertNotIsInstance(ctx.exception, BridgeTransportError)
self.assertEqual(spawn.state["n"], 1)
def test_transport_error_restarts_once_and_retries(self):
# First process dies mid-call (EOF); the bridge restarts once and the
# second process answers.
dead = _FakeProcess(self._handshake_frames()) # no id-3 frame -> EOF
good = _FakeProcess(
self._handshake_frames([{"jsonrpc": "2.0", "id": 3, "result": {"ok": True}}])
)
spawn = self._counting_spawn(dead, good)
bridge = McpBrainBridge(vault="/v", spawn=spawn)
bridge.start()
result = bridge.call_tool("brain_query", {"topic": "x"})
self.assertEqual(result, {"ok": True})
self.assertEqual(spawn.state["n"], 2)
def test_transport_error_retries_through_failed_restart(self):
# Regression: a restart whose OWN handshake dies must not abort the
# retry loop. dead-on-call -> dead-on-handshake -> good. The middle
# child EOFs during initialize, so _restart() raises; the loop must
# capture that and still reach the third, healthy child.
first = _FakeProcess(self._handshake_frames()) # no id-3 -> EOF on the call
broken = _FakeProcess([]) # EOF during handshake -> _restart() raises
good = _FakeProcess(
self._handshake_frames([{"jsonrpc": "2.0", "id": 3, "result": {"ok": True}}])
)
spawn = self._counting_spawn(first, broken, good)
bridge = McpBrainBridge(vault="/v", spawn=spawn)
bridge.start()
result = bridge.call_tool("brain_query", {"topic": "x"})
self.assertEqual(result, {"ok": True})
self.assertEqual(spawn.state["n"], 3)
self.assertTrue(broken.terminated)
class BridgeChildEnvironmentTests(unittest.TestCase):
"""Issue #173: what the MCP child inherits decides whether it can run.
The o2b wrapper resolves its own runtime with ``command -v bun``, so a
gateway PATH without Bun turns a perfectly good wrapper into exit 127 - and
the JSON-RPC channel only ever reported the consequence.
"""
def _handshake_frames(self):
return [
{"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2025-06-18"}},
{"jsonrpc": "2.0", "id": 2, "result": {"tools": []}},
]
def test_default_spawn_passes_the_env_overlay_to_popen(self):
proc = _FakeProcess(self._handshake_frames())
overlay = {"PATH": os.pathsep.join(("/opt/bun/bin", "/usr/bin")), "HOME": "/home/agent"}
with patch.object(bridge_module.subprocess, "Popen", return_value=proc) as popen:
McpBrainBridge(
vault="/v", command=("/home/agent/.local/bin/o2b", "mcp"), env=overlay
).start()
env = popen.call_args.kwargs["env"]
self.assertEqual(env["PATH"].split(os.pathsep)[0], "/opt/bun/bin")
# A copy, not the caller's dict: the bridge must not be mutated from
# under the child by a later edit of the overlay.
self.assertIsNot(env, overlay)
def test_default_spawn_inherits_when_no_env_overlay_is_given(self):
proc = _FakeProcess(self._handshake_frames())
with patch.object(bridge_module.subprocess, "Popen", return_value=proc) as popen:
McpBrainBridge(vault="/v").start()
self.assertIsNone(popen.call_args.kwargs["env"])
class BridgeStderrDiagnosticTests(unittest.TestCase):
"""Issue #173: the reason a child refused to start is on its stderr.
The JSON-RPC channel can only report the consequence ("unexpected EOF"),
which is a true statement about the transport and a useless one about the
cause. Draining stderr into a bounded tail lets the failure carry it.
"""
def test_handshake_failure_carries_the_child_stderr_excerpt(self):
# The child dies before its first stdout frame, so the transport sees
# EOF. The reason it died is on stderr and must reach the message.
proc = _FakeProcess(
[],
stderr_lines=[
b"error: 'bun' is not on PATH.\n",
b"Install it with: curl -fsSL https://bun.sh/install | bash\n",
],
)
with patch.object(bridge_module.subprocess, "Popen", return_value=proc):
bridge = McpBrainBridge(vault="/v")
with self.assertRaises(BridgeTransportError) as ctx:
bridge.start()
message = str(ctx.exception)
self.assertIn("unexpected EOF from MCP server", message)
self.assertIn("error: 'bun' is not on PATH.", message)
self.assertIn("https://bun.sh/install", message)
def test_handshake_failure_without_stderr_keeps_the_bare_message(self):
proc = _FakeProcess([])
with patch.object(bridge_module.subprocess, "Popen", return_value=proc):
bridge = McpBrainBridge(vault="/v")
with self.assertRaises(BridgeTransportError) as ctx:
bridge.start()
self.assertEqual(str(ctx.exception), "unexpected EOF from MCP server")
def test_an_unterminated_flood_is_clipped_as_it_arrives(self):
# `readline` returns only at a newline or at EOF, so a child that emits
# one enormous record with no newline would be held whole in the parent
# before any truncation could apply. The drain reads fixed-size chunks
# and clips the in-progress line instead.
flood = b"E" * (bridge_module.STDERR_TAIL_MAX_BYTES * 40)
proc = _FakeProcess([], stderr_lines=[flood])
with patch.object(bridge_module.subprocess, "Popen", return_value=proc):
bridge = McpBrainBridge(vault="/v")
with self.assertRaises(BridgeTransportError) as ctx:
bridge.start()
# Nothing the parent held was proportional to what the child wrote.
self.assertLessEqual(proc.stderr.max_read_size, bridge_module.STDERR_CHUNK_BYTES)
excerpt = str(ctx.exception).split("--- child stderr (last lines) ---\n", 1)[1]
self.assertLessEqual(len(excerpt), bridge_module.STDERR_TAIL_MAX_BYTES)
self.assertEqual(len(bridge._stderr_tail), 1)
def test_stderr_tail_is_bounded_to_the_last_lines(self):
noisy = [f"line-{i}\n".encode("utf-8") for i in range(500)]
proc = _FakeProcess([], stderr_lines=noisy)
with patch.object(bridge_module.subprocess, "Popen", return_value=proc):
bridge = McpBrainBridge(vault="/v")
with self.assertRaises(BridgeTransportError) as ctx:
bridge.start()
message = str(ctx.exception)
self.assertIn("line-499", message)
self.assertNotIn("line-0\n", message)
excerpt = message.split("--- child stderr (last lines) ---\n", 1)[1]
self.assertLessEqual(len(excerpt.splitlines()), bridge_module.STDERR_TAIL_LINES)
self.assertLessEqual(len(excerpt), bridge_module.STDERR_TAIL_MAX_BYTES)
class ProviderChildEnvironmentTests(unittest.TestCase):
"""The overlay the provider computes has to reach the bridge it builds."""
def tearDown(self):
_reset_shared_bridges_for_tests()
def test_initialize_hands_the_bun_bearing_env_to_the_bridge(self):
overlay = {"PATH": "/opt/bun/bin:/usr/bin"}
with (
patch(
"plugins.hermes.provider.McpBrainBridge", return_value=FakeBrainBridge()
) as factory,
patch("plugins.hermes.provider.config.resolve_vault", return_value="/vault"),
patch.object(OpenSecondBrainMemoryProvider, "_repo_root", return_value="/repo"),
patch.object(
OpenSecondBrainMemoryProvider,
"_resolve_command",
return_value=("/home/agent/.local/bin/o2b", "mcp"),
),
patch.object(OpenSecondBrainMemoryProvider, "_resolve_env", return_value=overlay),
):
OpenSecondBrainMemoryProvider().initialize("session-1", hermes_home="/hh")
self.assertEqual(factory.call_args.kwargs["env"], overlay)
def test_bridges_with_different_search_paths_are_not_shared(self):
paths = iter(({"PATH": "/a/bin"}, {"PATH": "/b/bin"}))
with (
patch(
"plugins.hermes.provider.McpBrainBridge",
side_effect=lambda **_: FakeBrainBridge(),
) as factory,
patch("plugins.hermes.provider.config.resolve_vault", return_value="/vault"),
patch.object(OpenSecondBrainMemoryProvider, "_repo_root", return_value="/repo"),
patch.object(
OpenSecondBrainMemoryProvider, "_resolve_command", return_value=("o2b", "mcp")
),
patch.object(
OpenSecondBrainMemoryProvider, "_resolve_env", side_effect=lambda: next(paths)
),
):
OpenSecondBrainMemoryProvider().initialize("session-1", hermes_home="/hh")
OpenSecondBrainMemoryProvider().initialize("session-2", hermes_home="/hh")
self.assertEqual(factory.call_count, 2)
class BridgeRequestDeadlineTests(unittest.TestCase):
"""A shared bridge is one stream, so an unanswered call is everyone's.
Before the bridge became shared, a child that stopped answering blocked the
one session that owned it. Sharing it made that block gateway-wide, and
nothing in this transport bounded a read - so the deadline is not a nicety
here, it is what keeps the fix from trading a descriptor leak for a stall.
"""
class _MuteReader:
"""Answers the handshake, then never answers again."""
def __init__(self, frames):
self._frames = list(frames)
self.reads_after_handshake = 0
def readline(self):
if self._frames:
return (json.dumps(self._frames.pop(0)) + "\n").encode("utf-8")
self.reads_after_handshake += 1
time.sleep(30)
return b""
class _MuteProcess:
pid = 4242
def __init__(self, frames):
self.stdin = io.BytesIO()
self.stdout = BridgeRequestDeadlineTests._MuteReader(frames)
self.stderr = io.BytesIO()
self.terminated = False
def poll(self):
return None
def terminate(self):
self.terminated = True
def wait(self, timeout=None):
return 0
HANDSHAKE = [
{"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2025-06-18"}},
{"jsonrpc": "2.0", "id": 2, "result": {"tools": []}},
]
def test_a_child_that_stops_answering_raises_instead_of_blocking(self):
spawned = []
def spawn(argv):
proc = self._MuteProcess(list(self.HANDSHAKE))
spawned.append(proc)
return proc
bridge = McpBrainBridge(vault="/v", spawn=spawn)
with patch.dict(os.environ, {REQUEST_TIMEOUT_ENV: "0.2"}):
bridge.start()
started = time.monotonic()
with self.assertRaises(BridgeTimeoutError):
bridge.call_tool("brain_query", {})
elapsed = time.monotonic() - started
# Bounded, not merely non-infinite: three attempts at 0.2s plus the
# existing backoff. The generous ceiling keeps this off the flake list
# on a loaded runner while still failing outright if the read is
# unbounded again.
self.assertLess(elapsed, 10.0)
# The stuck child is torn down rather than left holding the stream.
self.assertTrue(spawned[0].terminated)
def test_a_timed_out_bridge_does_not_hold_the_next_caller(self):
"""The property the shared bridge actually needs: the lock is released."""
def spawn(argv):
return self._MuteProcess(list(self.HANDSHAKE))
bridge = McpBrainBridge(vault="/v", spawn=spawn)
unblocked = threading.Event()
with patch.dict(os.environ, {REQUEST_TIMEOUT_ENV: "0.2"}):
bridge.start()
def first():
try:
bridge.call_tool("brain_query", {})
except BridgeTimeoutError:
pass
worker = threading.Thread(target=first, daemon=True)
worker.start()
time.sleep(0.05)
def second():
bridge.list_tools()
unblocked.set()
threading.Thread(target=second, daemon=True).start()
self.assertTrue(unblocked.wait(10.0))
def test_the_deadline_is_configurable_and_its_absence_is_explicit(self):
with patch.dict(os.environ, {}, clear=False):
os.environ.pop(REQUEST_TIMEOUT_ENV, None)
self.assertEqual(resolve_request_timeout(), DEFAULT_REQUEST_TIMEOUT_SECONDS)
with patch.dict(os.environ, {REQUEST_TIMEOUT_ENV: "45"}):
self.assertEqual(resolve_request_timeout(), 45.0)
# Non-positive is the deliberate escape hatch for a vault that
# legitimately outruns any bound.
with patch.dict(os.environ, {REQUEST_TIMEOUT_ENV: "0"}):
self.assertIsNone(resolve_request_timeout())
# A malformed value falls back to the default, never to no bound:
# a typo must not silently remove the protection.
with patch.dict(os.environ, {REQUEST_TIMEOUT_ENV: "soon"}):
self.assertEqual(resolve_request_timeout(), DEFAULT_REQUEST_TIMEOUT_SECONDS)
@unittest.skipUnless(os.name == "nt", "Windows-only: no watchdog wrapping")
def test_windows_children_are_not_wrapped_and_nothing_is_logged(self):
McpBrainBridge._watchdog_absent_warned = False
argv = ["o2b", "mcp"]
with patch.object(bridge_module.logger, "warning") as warn:
self.assertEqual(McpBrainBridge._watchdog_argv(argv), argv)
warn.assert_not_called()
@unittest.skipIf(os.name == "nt", "the parent-death watchdog wraps POSIX children only")
def test_a_missing_parent_death_watchdog_says_so_once(self):
McpBrainBridge._watchdog_absent_warned = False
argv = ["o2b", "mcp"]
with patch.dict(sys.modules, {"tools": None}):
with self.assertLogs("plugins.hermes.bridge", level="WARNING") as logs:
self.assertEqual(McpBrainBridge._watchdog_argv(argv), argv)
self.assertTrue(any("watchdog" in line for line in logs.output))
# Once per process: a property of the installation, not the call.
with patch.object(bridge_module.logger, "warning") as warn:
McpBrainBridge._watchdog_argv(argv)
warn.assert_not_called()
McpBrainBridge._watchdog_absent_warned = False
class FakeBrainBridgeTests(unittest.TestCase):
def test_records_calls_and_returns_canned_results(self):
bridge = FakeBrainBridge(
tools=[{"name": "brain_query"}],
results={"brain_query": {"items": []}},
)
bridge.start()
self.assertTrue(bridge.started)
self.assertEqual(bridge.list_tools(), [{"name": "brain_query"}])
self.assertEqual(bridge.call_tool("brain_query", {"q": "x"}), {"items": []})
self.assertEqual(bridge.calls, [("brain_query", {"q": "x"})])
bridge.stop()
self.assertTrue(bridge.stopped)
if __name__ == "__main__":
unittest.main()