Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 33 additions & 10 deletions examples/hermes-plugin/DEVELOPMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,14 @@ The active-session commit lifecycle was ported from
with the original author retained. The OpenViking adaptation uses a configurable
pending-token threshold instead of the original six-turn trigger.

Native memory mirroring is adapted from
[Hermes PR #100187](https://github.com/NousResearch/hermes-agent/pull/100187),
commit `32f75a9e6728a9a3d2f50a870dab3715a1f34fd7`, which continues
[austinlaw076's PR #85860](https://github.com/NousResearch/hermes-agent/pull/85860).
The external plugin uses relative imports and Hermes's context-preserving worker
helper. Its connection cache and session-commit lifecycle retain the later
OpenViking fixes.

Gateway sender attribution and recall scope adapt
[Hermes PR #105812](https://github.com/NousResearch/hermes-agent/pull/105812),
including liuhao1024's capture change from
Expand Down Expand Up @@ -54,8 +62,17 @@ install or package the OpenViking server.

## Validation

Use a Hermes checkout with its development dependencies installed. From that
checkout, run its canonical test runner against this directory:
Use a Hermes checkout with its development dependencies installed.

The complete mirror tests require the committed-entry event contract introduced
in [Hermes PR #118903](https://github.com/NousResearch/hermes-agent/pull/118903)
and merged through [#120003](https://github.com/NousResearch/hermes-agent/pull/120003)
(commit `5908e1aaa83e82aaf12541d7a9d90762d0b46a64`):
`MemoryManager` forwards `previous_content` for each successful replace/remove.
The legacy compatibility tests verify that missing metadata skips these remote
mutations. Do not substitute a guessed match in tests or production.

From that checkout, run its canonical test runner against this directory:

```bash
PYTHONPATH="$PWD${PYTHONPATH:+:$PYTHONPATH}" HERMES_TEST_FILE_RETRIES=0 \
Expand All @@ -66,14 +83,20 @@ PYTHONPATH="$PWD${PYTHONPATH:+:$PYTHONPATH}" HERMES_TEST_FILE_RETRIES=0 \
`--confcutdir` keeps pytest from importing the plugin as a test package before
Hermes loads it under its own namespace. The tests use temporary profile homes
and remove bundled-provider discovery.
They check external loading across profiles, HTTP tool dispatch, and cancelled
setup without changing existing configuration. Gateway tests use mock events
through Hermes's turn hooks and memory manager. They cover sender changes,
capture retries, commits, recall scopes, compression fallback, and missing
sender metadata. Setup tests cover both presets, confirmation, cancellation,
profile-local persistence, connection routes, and actual Hermes session keys.
Run the upstream OpenViking
provider tests in Hermes as well when changing provider behavior:
They cover external loading, profile isolation, setup, tools, session commits,
and native memory mirroring. The mirror suite includes ordered writes, restart
continuity, registry failures, connection isolation, and concurrent workers.
Gateway tests use mock events through Hermes's turn hooks and memory manager.
They cover sender changes, capture retries, commits, recall scopes, compression
fallback, and missing sender metadata. Setup tests cover both presets,
confirmation, cancellation, profile-local persistence, connection routes, and
actual Hermes session keys.
Provider-specific regression tests belong here and must use the shared external
loader fixture. Generic Hermes framework tests remain in Hermes.

For compatibility checks while Hermes still bundles OpenViking, also run its
provider tests. These load the bundled copy unless explicitly routed through the
external loader; they do not replace this directory's tests:

```bash
HERMES_TEST_FILE_RETRIES=0 scripts/run_tests.sh \
Expand Down
54 changes: 46 additions & 8 deletions examples/hermes-plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -275,17 +275,55 @@ OpenViking server auto-commit is disabled by default, so an accepted message
whose explicit commit fails normally remains live and unextracted until it is
manually committed.

Hermes built-in `memory` tool additions are mirrored to OpenViking after the
local memory operation succeeds:
Successful Hermes built-in `memory` mutations are mirrored to OpenViking in
order. The active profile records each mirrored entry's exact URI in
`$HERMES_HOME/openviking/memory_mirror_registry.json`:

| Hermes action | OpenViking operation |
|---------------|----------------------|
| `add` | `content/write` with `mode=create` under user memory, or the configured peer memory directory |

Built-in `replace` and `remove` operations are not mirrored because Hermes
native memory entries do not yet carry stable OpenViking file URIs. Use
`viking_forget` when the user explicitly asks to delete a specific OpenViking
memory URI.
| `add` | Create a file under user memory or the configured peer, then record its URI |
| `replace` | Match the committed event's full previous content and target, update the same URI, and wait for semantic/vector refresh |
| `remove` | Match the committed event's full previous content and target, delete that exact URI, and wait for semantic cleanup |

Replacing a mapped entry recreates its file if it was deleted directly in
OpenViking, for example with `viking_forget`.

The registry stores the current entry text and a connection fingerprint, not
the raw API key. Endpoint, credentials, user, account, and peer changes isolate
the new connection from earlier mappings. New files require a server-confirmed
user identity. Missing or ambiguous mappings block replacement and deletion
with a warning; the plugin never selects a target by semantic similarity.

Replacement and deletion require Hermes to provide authoritative
`previous_content` metadata from the native-store commit. Older Hermes versions
without this event contract skip those mirror operations with a warning; native
local memory still changes. The plugin never falls back to matching the caller's
`old_text` against its partial registry.
The required event contract was merged in
[Hermes PR #120003](https://github.com/NousResearch/hermes-agent/pull/120003)
(commit `5908e1aaa83e82aaf12541d7a9d90762d0b46a64`), which landed
[#118903](https://github.com/NousResearch/hermes-agent/pull/118903).

Only entries created by this mirror have mappings. Session-extracted memories,
explicit `viking_remember` results, and copies created before this registry are
outside its scope. Use `viking_forget` with an exact URI to remove those copies.

The mirror is asynchronous. Hermes saves its local memory first. Rejected remote
writes leave the registry unchanged and produce a warning. Additions do not wait
for indexing, so the mirror does not report later indexing failures. For `replace`,
if the server reports that the file changed but indexing failed, the registry
retains the new content and exact URI; a warning reports the indexing failure
because search results may be stale. There is no durable replay. A remote mutation
followed by a failed registry save can also cause drift. Operations are ordered
per provider; registry updates are serialized across instances sharing a profile
in one process, not across processes.

Registry files use mode `0600` on POSIX. Protect the profile with normal account
and filesystem permissions on Windows. An unreadable, invalid, or unsupported
registry blocks all mirror writes. Stop Hermes before restoring a valid backup.
For an unsupported version, use a plugin version that supports it. Renaming a
damaged registry starts a new registry but leaves earlier remote copies without
mappings; those copies need manual cleanup by exact URI.

`viking_forget` is intentionally narrow. It only accepts concrete user memory
file URIs, such as
Expand Down
70 changes: 51 additions & 19 deletions examples/hermes-plugin/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
_SYNC_TRACE_ENV = "HERMES_OPENVIKING_SYNC_TRACE"
_RECALL_QUERY_MIN_CHARS = 5
_RECALL_MIN_TIMEOUT_SECONDS = 0.05
_DEFAULT_RECALL_REQUEST_TIMEOUT_SECONDS = 3.0
_READ_BATCH_LIMIT = 3
_READ_BATCH_FULL_LIMIT = 2500
_LEVEL_ENDPOINTS = {"abstract": "/api/v1/content/abstract", "overview": "/api/v1/content/overview", "full": "/api/v1/content/read"}
Expand Down Expand Up @@ -105,7 +106,7 @@ def _cfg_field(key: str, description: str, **extra) -> dict:
_cfg_field("recall_max_injected_chars", "Maximum total characters injected by recall", type="integer", minimum=100, maximum=50000, default=4000),
_cfg_field("profile_token_budget", "Maximum session-start memory tokens injected", type="integer", minimum=500, maximum=50000, default=6000),
_cfg_field("recall_timeout_seconds", "Total timeout for recall (seconds)", **_NUM, default=4.0),
_cfg_field("recall_request_timeout_seconds", "Per-request timeout for recall (seconds)", **_NUM, default=3.0),
_cfg_field("recall_request_timeout_seconds", "Per-request timeout for recall (seconds)", **_NUM, default=_DEFAULT_RECALL_REQUEST_TIMEOUT_SECONDS),
_cfg_field("recall_full_read_limit", "Max full L2 content reads per recall", type="integer", minimum=0, maximum=100, default=2),
_cfg_field("recall_prefer_abstract", "Use abstracts instead of full L2 reads", type="boolean", default=False),
_cfg_field("recall_resources", "Include resources in recall", type="boolean", default=False),
Expand Down Expand Up @@ -1295,7 +1296,7 @@ def __init__(self):
# _failed_refresh = (settings key, monotonic ts) of the last failure -> cooldown gate.
self._session_state_lock = threading.RLock()
(self._inflight_lock, self._deferred_commit_lock, self._committed_session_lock,
self._client_refresh_lock, self._runtime_start_lock, self._memory_write_lock,
self._client_refresh_lock, self._runtime_start_lock, self._native_memory_mirror_lock,
self._writer_commit_lock) = (threading.Lock() for _ in range(7))
# Writers keyed by the sid they POST under so a commit can drain all of them.
# Guards the (_session_id, _turn_count) pair. sync_turn runs on the MemoryManager's background sync
Expand All @@ -1305,7 +1306,6 @@ def __init__(self):
self._inflight_writers: Dict[str, Set[threading.Thread]] = {}
self._deferred_commit_threads: Set[threading.Thread] = set()
self._commit_scope: Optional[_CommitScope] = None
self._memory_write_threads: Set[threading.Thread] = set()
self._profile_prefetched_sessions: Set[str] = set()
self._conn_snapshot: Optional[tuple] = None
self._failed_refresh: Optional[tuple] = None
Expand Down Expand Up @@ -1949,7 +1949,7 @@ def _head_only() -> str:
tail = cls._take_tokens("\n".join(lines[8:]), remaining - cls._token_units(head), from_end=True).lstrip()
return f"{head}{marker}{tail}" if tail else _head_only()

def _user_space(self, client=None, *, timeout: Optional[float] = None) -> str:
def _user_space(self, client=None, *, timeout: Optional[float] = None, require_confirmed: bool = False) -> str:
"""Resolve the user space, caching only a confirmed connection identity.

Use the client's snapshot even when a reload has replaced the active connection.
Expand All @@ -1964,6 +1964,11 @@ def _user_space(self, client=None, *, timeout: Optional[float] = None) -> str:
if snapshot is not None:
self._user_space_cache = (snapshot, resolved)
return resolved
if require_confirmed:
raise RuntimeError(
"OpenViking server did not confirm the current user identity; "
"leaving OpenViking unchanged"
)
return str(getattr(active, "_user", "") or getattr(self, "_user", "") or "default").strip() or "default"

@staticmethod
Expand Down Expand Up @@ -2690,7 +2695,14 @@ def on_session_switch(self, new_session_id: str, *, parent_session_id: str = "",

# -- memory mirroring -----------------------------------------------------

def _build_memory_uri(self, subdir: str, *, client=None, timeout: Optional[float] = None) -> str:
def _build_memory_uri(
self,
subdir: str,
*,
client=None,
timeout: Optional[float] = None,
require_confirmed_user: bool = False,
) -> str:
"""Explicit-uid user memory URI, under the configured peer when one is set.

The peer is read from the captured client (not the provider) so a config
Expand All @@ -2702,11 +2714,27 @@ def _build_memory_uri(self, subdir: str, *, client=None, timeout: Optional[float
active_client = client if client is not None else getattr(self, "_client", None)
agent = str(getattr(active_client, "_agent", getattr(self, "_agent", "")) or "").strip()
peer_prefix = f"peers/{agent}/" if agent else ""
return f"viking://user/{self._user_space(active_client, timeout=timeout)}/{peer_prefix}memories/{subdir}/mem_{uuid.uuid4().hex[:12]}.md"

def on_memory_write(self, action: str, target: str, content: str, metadata: Optional[Dict[str, Any]] = None) -> None:
"""Mirror successful built-in memory additions to OpenViking."""
if action != "add" or not content or not self._ensure_client():
identity_timeout = timeout
if require_confirmed_user and identity_timeout is None:
identity_timeout = _DEFAULT_RECALL_REQUEST_TIMEOUT_SECONDS
user_space = self._user_space(
active_client,
timeout=identity_timeout,
require_confirmed=require_confirmed_user,
)
return f"viking://user/{user_space}/{peer_prefix}memories/{subdir}/mem_{uuid.uuid4().hex[:12]}.md"

def on_memory_write(
self,
action: str,
target: str,
content: str,
metadata: Optional[Dict[str, Any]] = None,
) -> None:
"""Mirror successful built-in memory mutations to OpenViking."""
if action not in {"add", "replace", "remove"} or not self._ensure_client():
return
if action in {"add", "replace"} and not content:
return
subdir = _MEMORY_WRITE_TARGET_SUBDIR_MAP.get(target, "preferences")
try:
Expand All @@ -2715,15 +2743,17 @@ def on_memory_write(self, action: str, target: str, content: str, metadata: Opti
logger.debug("OpenViking memory mirror client creation failed: %s", e)
return

def _write():
try:
uri = self._build_memory_uri(subdir, client=client, timeout=_RECALL_MIN_TIMEOUT_SECONDS)
client.post("/api/v1/content/write", {"uri": uri, "content": content, "mode": "create"})
except Exception as e:
logger.debug("OpenViking memory mirror failed: %s", e)
from .native_memory_mirror import enqueue_native_memory_write

self._spawn_tracked("openviking-memwrite", _write, self._memory_write_lock, lambda: self._memory_write_threads,
skip_if=lambda: self._shutting_down)
enqueue_native_memory_write(
self,
action,
target,
content,
metadata=metadata,
subdir=subdir,
client=client,
)

# -- tools ------------------------------------------------------------------

Expand All @@ -2746,10 +2776,12 @@ def shutdown(self) -> None:
# the autostart waiter (a daemon blocked on health probes would SIGABRT CPython at
# Py_FinalizeEx); _shutting_down makes its wait loop bail so the join lands.
self._shutting_down = True
from .native_memory_mirror import shutdown_native_memory_mirror

shutdown_native_memory_mirror(self, timeout=5.0)
workers: List[threading.Thread] = []
for lock, group in ((self._inflight_lock, lambda: [t for g in self._inflight_writers.values() for t in g]),
(self._deferred_commit_lock, lambda: list(self._deferred_commit_threads)),
(self._memory_write_lock, lambda: list(self._memory_write_threads)),
(self._runtime_start_lock, lambda: [self._runtime_start_thread] if self._runtime_start_thread is not None else [])):
with lock:
workers += group()
Expand Down
Loading