The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(plugins): on_session_delete review findings
Teknium627ce0355641
diff --git a/hermes_state_common.py b/hermes_state_common.pyindex a45358749dd..98b7a5a9e69 100644--- a/hermes_state_common.py+++ b/hermes_state_common.py@@ -395,29 +395,36 @@ def _id_chunks(ids, size: int = _SQL_IN_CHUNK):def emit_session_deleted(db, deleted_ids, *, reason, primary=None, sessions_dir=None):"""Fire ``on_session_delete`` after a committed delete or deliberate archive (#124511).- Call only after the write transaction commits, with the ids it actually removed (or, for- ``reason="archive"``, hid). *primary* is the session the caller asked for; without it the- first removed id stands in (bulk sweeps). ``deleted_ids`` rides along only when more than- one row went. Late-bound and fail-open: the state layer never imports ``hermes_cli`` at module- top level, and a missing or raising plugin stack never breaks the delete.+ Call right after the write transaction commits (before follow-up cleanup that can raise), with+ the ids it removed or, for ``reason="archive"``, hid. *primary* is the session the caller asked+ for; without it the first id stands in (bulk sweeps). ``deleted_ids`` rides along when more+ than one row went. Dispatch runs under the store's own profile home, so a process touching+ another profile's store (``sessions repair-profiles``) reaches THAT profile's plugins.+ Late-bound and fail-open: never breaks the delete."""ids = sorted({sid for sid in (deleted_ids or ()) if isinstance(sid, str) and sid})if not ids:returntry:from hermes_cli.lifecycle import invoke_hook- from hermes_constants import profile_name_for_home+ from hermes_constants import (+ get_hermes_home, profile_name_for_home, reset_hermes_home_override, set_hermes_home_override,+ )- payload: dict = {- "session_id": primary if primary in ids else ids[0],- "reason": reason,- "profile": profile_name_for_home(os.path.dirname(os.fspath(db.db_path))),- }+ home = os.path.dirname(os.path.abspath(os.fspath(db.db_path)))+ profile = profile_name_for_home(home)+ payload: dict = {"session_id": primary if primary in ids else ids[0], "reason": reason, "profile": profile}if len(ids) > 1:payload["deleted_ids"] = idsif sessions_dir is not None:payload["sessions_dir"] = str(sessions_dir)- invoke_hook("on_session_delete", **payload)+ rebind = profile is not None and os.path.realpath(home) != os.path.realpath(get_hermes_home())+ token = set_hermes_home_override(home) if rebind else None+ try:+ invoke_hook("on_session_delete", **payload)+ finally:+ if token is not None:+ reset_hermes_home_override(token)except Exception:logger.warning("on_session_delete dispatch failed", exc_info=True)diff --git a/hermes_state_maintenance.py b/hermes_state_maintenance.pyindex c5d699504c9..9ea68279ec7 100644--- a/hermes_state_maintenance.py+++ b/hermes_state_maintenance.py@@ -132,12 +132,11 @@ class SessionMaintenanceMixin:self._delete_unreferenced_system_prompts(conn)return idsremoved_ids = self._execute_write(_do) or []+ emit_session_deleted(self, removed_ids, reason="ghost_prune", sessions_dir=sessions_dir)from hermes_state_media import collect_retired_mediacollect_retired_media(self)for sid in removed_ids if sessions_dir else ():self._remove_session_files(sessions_dir, sid)- if removed_ids:- emit_session_deleted(self, removed_ids, reason="ghost_prune", sessions_dir=sessions_dir)return len(removed_ids)def _guarded_ids(self, conn, ids: Iterable[str]) -> set:@@ -400,14 +399,14 @@ class SessionMaintenanceMixin:self._delete_unreferenced_system_prompts(conn)return len(session_ids)count = self._execute_write(_do)+ if count:+ emit_session_deleted(self, removed_ids, reason="prune", sessions_dir=sessions_dir)from hermes_state_media import collect_retired_mediacollect_retired_media(self)for sid in removed_ids:self._remove_session_files(sessions_dir, sid)if deleted_ids is not None:deleted_ids.extend(removed_ids)- if count:- emit_session_deleted(self, removed_ids, reason="prune", sessions_dir=sessions_dir)return countdef _page_pragmas(self, names: tuple[str, ...], fail_msg: str) -> Optional[list]:diff --git a/hermes_state_runtime.py b/hermes_state_runtime.pyindex 0ec37531785..ebc56f2e526 100644--- a/hermes_state_runtime.py+++ b/hermes_state_runtime.py@@ -5,6 +5,7 @@ SessionDB transaction owner, including its inode guard and SQLite retry policy."""import jsonimport uuid+from typing import NamedTuple, Optionalfrom agent.conversation_compression_archive import ABSORBED_ROW_IDSfrom agent.message_metadata import (@@ -13,6 +14,12 @@ from agent.message_metadata import (from hermes_state_keys import admission_fingerprint+class SessionGoneEvent(NamedTuple):+ """The ``on_session_delete`` event a committed runtime mutation owes its plugins."""+ session_ids: tuple+ reason: str++class RuntimeStoreError(ValueError):"""A refusal by the state authority. ``reason`` is the bounded wire code (callers compare it as astring); ``field`` and ``detail`` name the check that fired and why, so a client and the gateway@@ -449,15 +456,12 @@ def mutate_runtime_session(db, *, epoch: int, principal_id: str, session_id: strkey, digest = mutation_receipt_key(principal_id, session_id, request_id, operation=operation, payload=payload,expected_revision=expected_revision, expected_generation=expected_generation)- # (ids, reason) for on_session_delete; reset per attempt (the write retries) and empty on replay.- gone: list = []-- def write(conn):- gone.clear()+ def write(conn) -> tuple[dict, Optional[SessionGoneEvent]]:+ """The receipt result plus the on_session_delete event this commit owes (None on replay)."""_epoch(conn, epoch)replay = replay_mutation_receipt(conn, key, digest)if replay is not None:- return replay+ return replay, Nonesession = conn.execute('SELECT * FROM sessions WHERE id=?', (session_id,)).fetchone()if session is None and operation != 'import':raise RuntimeStoreError('not_found')@@ -479,12 +483,13 @@ def mutate_runtime_session(db, *, epoch: int, principal_id: str, session_id: str# The branch commit's own idle rule (queued input too), before the owner starts servers.from hermes_state_mutation_guards import require_idlerequire_idle(db, conn, list({session_id, snapshot['target']}))- return {'snapshot': snapshot}+ return {'snapshot': snapshot}, Noneaffected, projection = apply_action(db, conn, session_id, operation, payload, prepared=_prepared)+ event = Noneif operation == 'delete':- gone[:] = [projection.get('deleted_ids') or [session_id], 'delete']+ event = SessionGoneEvent(tuple(projection.get('deleted_ids') or (session_id,)), 'delete')elif payload.get('archived') is True and session is not None and not session['archived']:- gone[:] = [[session_id], 'archive']+ event = SessionGoneEvent(tuple(affected) or (session_id,), 'archive')conn.executemany('UPDATE sessions SET runtime_revision=runtime_revision+1 WHERE id=?',[(target,) for target in affected])updated = conn.execute('SELECT * FROM sessions WHERE id=?', (session_id,)).fetchone()@@ -493,11 +498,11 @@ def mutate_runtime_session(db, *, epoch: int, principal_id: str, session_id: str'operation': operation, **projection}conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)',(key, _json({'digest': digest, 'result': result})))- return result- result = db._execute_write(write)- if gone:+ return result, event+ result, event = db._execute_write(write)+ if event is not None:from hermes_state_common import emit_session_deleted- emit_session_deleted(db, gone[0], reason=gone[1], primary=session_id)+ emit_session_deleted(db, event.session_ids, reason=event.reason, primary=session_id)return resultdiff --git a/hermes_state_sessions.py b/hermes_state_sessions.pyindex 8ba80c448f1..d3f28a7c0c3 100644--- a/hermes_state_sessions.py+++ b/hermes_state_sessions.py@@ -947,7 +947,7 @@ class SessionSessionsMixin:return ids, bool(archived and ids and row is not None and not row[0])ids, newly_archived = self._execute_write(_do)if newly_archived and notify:- emit_session_deleted(self, [session_id], reason="archive")+ emit_session_deleted(self, ids, reason="archive", primary=session_id)return bool(ids)def _auto_archive_lineage(self, session_id: str) -> bool:@@ -1761,12 +1761,12 @@ class SessionSessionsMixin:removed_ids.extend(scope)return Truedeleted = self._execute_write(_do)+ if deleted:+ emit_session_deleted(self, removed_ids, reason="delete", primary=session_id, sessions_dir=sessions_dir)from hermes_state_media import collect_retired_mediacollect_retired_media(self)for sid in removed_ids:self._remove_session_files(sessions_dir, sid)- if deleted:- emit_session_deleted(self, removed_ids, reason="delete", primary=session_id, sessions_dir=sessions_dir)return bool(deleted)def discard_unadmitted_session(self, session_id: str) -> bool:@@ -1823,11 +1823,12 @@ class SessionSessionsMixin:self._delete_unreferenced_system_prompts(conn)return Truedeleted = self._execute_write(_do)+ if deleted:+ emit_session_deleted(self, [session_id], reason="empty_sweep", sessions_dir=sessions_dir)from hermes_state_media import collect_retired_mediacollect_retired_media(self)if deleted:self._remove_session_files(sessions_dir, session_id)- emit_session_deleted(self, [session_id], reason="empty_sweep", sessions_dir=sessions_dir)return deleteddef delete_sessions(@@ -1911,13 +1912,13 @@ class SessionSessionsMixin:# 3 rows, however many physical links those rows had.return len(existing)count = self._execute_write(_do)+ if count:+ emit_session_deleted(self, removed_ids, reason="delete", primary=unique_ids[0] if len(unique_ids) == 1 else None,+ sessions_dir=sessions_dir)from hermes_state_media import collect_retired_mediacollect_retired_media(self)for sid in removed_ids:self._remove_session_files(sessions_dir, sid)- if count:- emit_session_deleted(self, removed_ids, reason="delete", primary=unique_ids[0] if len(unique_ids) == 1 else None,- sessions_dir=sessions_dir)return count# Shared by count_empty_sessions / delete_empty_sessions so badge and sweep agree. message_count@@ -1956,12 +1957,12 @@ class SessionSessionsMixin:self._delete_unreferenced_system_prompts(conn)return len(session_ids)count = self._execute_write(_do)+ if count:+ emit_session_deleted(self, removed_ids, reason="empty_sweep", sessions_dir=sessions_dir)from hermes_state_media import collect_retired_mediacollect_retired_media(self)for sid in removed_ids:self._remove_session_files(sessions_dir, sid)- if count:- emit_session_deleted(self, removed_ids, reason="empty_sweep", sessions_dir=sessions_dir)return countdef archive_sessions(diff --git a/tests/hermes_state/test_session_delete_hook.py b/tests/hermes_state/test_session_delete_hook.pyindex e81582a330a..f9f805aa4cb 100644--- a/tests/hermes_state/test_session_delete_hook.py+++ b/tests/hermes_state/test_session_delete_hook.py@@ -53,6 +53,12 @@ def test_every_delete_and_archive_path_fires_once_after_commit(db, hook):db.append_message(sid, role="user", content="hi")db.end_session("empty", "done")db.end_session("old", "done")+ for tip in ("arch", "desk-arch"): # compression chains: archiving the tip hides the root too+ db.create_session(f"{tip}-root", source="cli")+ db.append_message(f"{tip}-root", role="user", content="hi")+ db.end_session(f"{tip}-root", "compression")+ db._execute_write(lambda c, t=tip: c.execute(+ "UPDATE sessions SET parent_session_id = ? WHERE id = ?", (f"{t}-root", t)))assert db.delete_session("cli") # hermes sessions delete, /exit --deleteassert db.delete_session("missing") is False # unknown id: silent@@ -73,8 +79,8 @@ def test_every_delete_and_archive_path_fires_once_after_commit(db, hook):("empty", "empty_sweep", None, None),("old", "prune", None, None),("desk", "delete", None, None),- ("arch", "archive", None, True),- ("desk-arch", "archive", None, True),+ ("arch", "archive", ["arch", "arch-root"], True),+ ("desk-arch", "archive", ["desk-arch", "desk-arch-root"], True),]assert all(e["profile"] == events[0]["profile"] for e in events)diff --git a/website/docs/user-guide/features/hooks.md b/website/docs/user-guide/features/hooks.mdindex 19e8f2c8b03..ed30ffec051 100644--- a/website/docs/user-guide/features/hooks.md+++ b/website/docs/user-guide/features/hooks.md@@ -1108,20 +1108,6 @@ def my_callback(session_id: str, reason: str, profile: str | None, **kwargs):**Use cases:** Delete a per-session sidecar database or cache directory, close a linked task when the user archives its chat, emit "session deleted" analytics.------------|------|-------------|-| `session_id` | `str` | The session that was deleted. Always present. |-| `deleted_ids` | `list[str]`, optional | Full set removed by the operation, including cascade-deleted delegate children and every row in a bulk delete. Present when the count differs from 1. |-| `reason` | `str`, optional | Why the delete happened (`"prune"`, `"ghost_prune"`, `"empty_sweep"`, …). |-| `sessions_dir` | `str`, optional | Absolute path of the profile's `sessions/` dir, so a plugin does not have to re-derive the per-profile home. |--**Fires:** Post-commit only, and only when the delete actually happened (unknown ids in a bulk delete are skipped silently). Return ignored; a failing callback is logged and skipped like every other observer. The payload carries no message content — only ids, the reason, and the directory.--**Delivery scope:** Process-local — the callback runs only in the process that committed the delete. It is not a durable cross-process delivery channel, and it carries no exactly-once guarantee: external side effects driven from the callback should tolerate a missed or duplicated invocation.--**Return value:** Ignored.--**Use cases:** Delete a per-session sidecar database or cache directory, emit "session deleted" analytics, release per-session external resources.----See the **[Build a Plugin guide](../../developer-guide/plugins/index.md)** for the full walkthrough including tool schemas, handlers, and advanced hook patterns.