Skip to content

The agent that grows with you

fix(sessions): `hermes sessions prune` runs through the live gateway instead of refusing

Tekniumc71e6c791b9c
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index 241040ace27..a23cc260897 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -4482,6 +4482,16 @@ export interface SessionMutateResult {
revision?: number | null
[key: string]: unknown
}
+/** Exactly one of ``filters`` (``SessionDB.prune_sessions`` keyword filters, as ``hermes sessions prune`` builds them) or ``never_active_days`` (``--never-active``). */
+export interface SessionPruneParams {
+ filters?: Record<string, unknown> | null
+ never_active_days?: number | null
+}
+export interface SessionPruneResult {
+ deleted: number
+ routing_deleted?: number | null
+ skipped?: number | null
+}
export interface CanonicalSessionInfoParams {
session_id: string
}
@@ -6371,6 +6381,8 @@ export interface CanonicalRpcMethods {
'session.list': { params: CanonicalListParams; result: CanonicalListResult }
/** Revision-fenced, retry-idempotent session edit (rename, archive, sidebar, branch, delete, rewind, reset, model, compress, import). */
'session.mutate': { params: SessionMutateParams; result: SessionMutateResult }
+ /** Local operator only: the owner deletes the ended sessions `hermes sessions prune` selected, skipping busy sessions and retained reset owners. */
+ 'session.prune': { params: SessionPruneParams; result: SessionPruneResult }
'session.redirect': { params: CanonicalCorrectionParams; result: CanonicalCorrectionResult }
'session.resume': { params: CanonicalResumeParams; result: CanonicalSnapshot }
'session.steer': { params: CanonicalCorrectionParams; result: CanonicalCorrectionResult }
@@ -6414,6 +6426,7 @@ export const CANONICAL_RPC_METHODS = [
'session.interrupt',
'session.list',
'session.mutate',
+ 'session.prune',
'session.redirect',
'session.resume',
'session.steer',
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index d9354b7cbc7..bb2faa8061b 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -35073,6 +35073,77 @@
"title": "SessionParams",
"type": "object"
},
+ "SessionPruneParams": {
+ "additionalProperties": false,
+ "description": "Exactly one of ``filters`` (``SessionDB.prune_sessions`` keyword filters, as\n``hermes sessions prune`` builds them) or ``never_active_days`` (``--never-active``).",
+ "properties": {
+ "filters": {
+ "anyOf": [
+ {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Filters"
+ },
+ "never_active_days": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Never Active Days"
+ }
+ },
+ "title": "SessionPruneParams",
+ "type": "object"
+ },
+ "SessionPruneResult": {
+ "additionalProperties": false,
+ "properties": {
+ "deleted": {
+ "title": "Deleted",
+ "type": "integer"
+ },
+ "routing_deleted": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Routing Deleted"
+ },
+ "skipped": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Skipped"
+ }
+ },
+ "required": [
+ "deleted"
+ ],
+ "title": "SessionPruneResult",
+ "type": "object"
+ },
"SessionReclaimedPayload": {
"additionalProperties": false,
"description": "``session_lifecycle._announce_session_reclaimed`` (broadcast).",
@@ -44217,6 +44288,24 @@
}
}
},
+ {
+ "name": "session.prune",
+ "summary": "Local operator only: the owner deletes the ended sessions `hermes sessions prune` selected, skipping busy sessions and retained reset owners.",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/SessionPruneParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/SessionPruneResult"
+ }
+ }
+ },
{
"name": "session.redirect",
"summary": "",
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index 89a26dd870b..0a11d2e7926 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -96,6 +96,8 @@ class AuthorityConnection:
from gateway.session_images import attach_bytes
from functools import partial
handlers['image.attach_bytes'] = partial(attach_bytes, self)
+ from gateway.session_prune import prune
+ handlers['session.prune'] = partial(prune, self)
return handlers
async def dispatch(self, request):
diff --git a/gateway/session_mutations.py b/gateway/session_mutations.py
index d224394a1b9..8441be48bac 100644
--- a/gateway/session_mutations.py
+++ b/gateway/session_mutations.py
@@ -196,14 +196,20 @@ def _project_committed(authority, ref, operation, result):
if operation == 'delete':
# Repeat local retirement on an exact retry too: publication may have
# failed after the transaction committed. Never repeat the event.
- store = getattr(authority.runner, 'session_store', None)
- if store is not None:
- store.retire_runtime_sessions(result['deleted_ids'])
- from gateway.session_policy import release_launch_secrets
- release_launch_secrets(authority, result['deleted_ids'])
- for sid in result['deleted_ids']:
- candidate = authority.sessions.pop(sid, None)
- if candidate is not None:
- evict = getattr(authority.runner, '_evict_cached_agent', None)
- if callable(evict):
- evict(candidate.route)
+ retire_live_sessions(authority, result['deleted_ids'])
+
+
+def retire_live_sessions(authority, session_ids):
+ """Drop committed deletions from this owner's memory: routes, launch secrets, live sessions
+ and their cached agents. Shared by canonical delete and the owner-run bulk prune."""
+ store = getattr(authority.runner, 'session_store', None)
+ if store is not None:
+ store.retire_runtime_sessions(session_ids)
+ from gateway.session_policy import release_launch_secrets
+ release_launch_secrets(authority, session_ids)
+ for sid in session_ids:
+ candidate = authority.sessions.pop(sid, None)
+ if candidate is not None:
+ evict = getattr(authority.runner, '_evict_cached_agent', None)
+ if callable(evict):
+ evict(candidate.route)
diff --git a/gateway/session_prune.py b/gateway/session_prune.py
new file mode 100644
index 00000000000..5b4c0f8d1e1
--- /dev/null
+++ b/gateway/session_prune.py
@@ -0,0 +1,61 @@
+"""``session.prune``: the owner runs `hermes sessions prune` for its own store.
+
+The CLI computes the filters and shows the preview from a read-only view; the delete itself is
+this owner's write, through the same ``prune_sessions`` / ``retire_prunable`` path housekeeping
+uses (busy sessions and the logical owner of a retained reset child are skipped). A CLI writing
+the store under a live gateway would be a second writer, so it never does.
+"""
+import asyncio
+from pathlib import Path
+
+from hermes_state_runtime import RuntimeStoreError
+
+_SCALARS = (type(None), bool, int, float, str)
+
+
+def _filters(raw):
+ from hermes_state_maintenance import _PRUNE_FILTER_NAMES
+ if (not isinstance(raw, dict) or set(raw) - (_PRUNE_FILTER_NAMES | {'older_than_days'})
+ or not all(isinstance(value, _SCALARS) for value in raw.values())):
+ raise RuntimeStoreError('invalid_params')
+ return dict(raw)
+
+
+async def prune(connection, ref, params):
+ authority, actor = connection.authority, connection.actor
+ # Store-wide deletion across every principal's rows: the local operator only (a ticket from
+ # this host's private control socket), never a remote or browser grant.
+ if not connection.native_owner or 'session:operator' not in actor.capabilities:
+ raise RuntimeStoreError('permission_denied')
+ if actor.profile_id != authority.profile_id:
+ raise RuntimeStoreError('profile_mismatch')
+ never_active = params.get('never_active_days')
+ if ('filters' in params) == (never_active is not None) or (
+ never_active is not None and (isinstance(never_active, bool) or not isinstance(never_active, (int, float))
+ or never_active < 0)):
+ raise RuntimeStoreError('invalid_params')
+ filters = _filters(params['filters']) if 'filters' in params else None
+ authority._require_admission_open()
+ from gateway.session_runtime_workers import track_mutation
+ task = track_mutation(authority, _apply(authority, filters, never_active))
+ return await asyncio.shield(task)
+
+
+async def _apply(authority, filters, never_active):
+ from hermes_constants import get_hermes_home
+ from gateway.session_mutations import retire_live_sessions
+ # Same transcript dir the CLI's local prune unlinks under (dispatch runs in the owner's scope).
+ sessions_dir = Path(get_hermes_home()) / 'sessions'
+ deleted_ids = []
+ if filters is None:
+ deleted, routing, skipped = await asyncio.to_thread(
+ authority.db.prune_never_active_keyed_sessions, older_than_days=float(never_active),
+ sessions_dir=sessions_dir, deleted_ids=deleted_ids)
+ result = {'deleted': deleted, 'routing_deleted': routing, 'skipped': skipped}
+ else:
+ deleted = await asyncio.to_thread(
+ authority.db.prune_sessions, sessions_dir=sessions_dir, exclude_active_write_guards=True,
+ deleted_ids=deleted_ids, **filters)
+ result = {'deleted': deleted}
+ retire_live_sessions(authority, deleted_ids)
+ return result
diff --git a/hermes_cli/gateway_client.py b/hermes_cli/gateway_client.py
index 581d3d04e5f..205015a753f 100644
--- a/hermes_cli/gateway_client.py
+++ b/hermes_cli/gateway_client.py
@@ -182,15 +182,20 @@ def _session_ticket(home: Path, endpoint, *, purpose="interactive", scope=None)
@asynccontextmanager
-async def connect_gateway():
+async def connect_gateway(endpoint=None):
+ """Attach to this home's owner. ``endpoint``: an already-discovered ready owner to dial as-is
+ (maintenance that must never start a gateway); default ensures one, starting it if needed."""
from websockets.asyncio.client import connect
from hermes_constants import get_hermes_home
from hermes_cli.gateway_runtime import ensure_gateway_runtime
from urllib.parse import urlsplit
- remote = os.environ.get("HERMES_TUI_GATEWAY_URL", "").strip()
+ remote = "" if endpoint is not None else os.environ.get("HERMES_TUI_GATEWAY_URL", "").strip()
protocols = None
- if remote:
+ if endpoint is not None:
+ ticket = await asyncio.to_thread(_session_ticket, get_hermes_home().resolve(), endpoint)
+ url, protocols = gateway_ws_target(endpoint, ticket)
+ elif remote:
parsed = urlsplit(remote)
if parsed.scheme not in {"ws", "wss"} or not parsed.hostname:
raise GatewayClientError("Invalid explicit gateway WebSocket URL; no local fallback")
diff --git a/hermes_cli/sessions_cmd.py b/hermes_cli/sessions_cmd.py
index 204b4977e26..c93ea686819 100644
--- a/hermes_cli/sessions_cmd.py
+++ b/hermes_cli/sessions_cmd.py
@@ -665,9 +665,19 @@ def _prune_never_active_keyed(db, args):
if not args.yes and not _confirm_prompt(f"Delete {len(candidates)} session(s)? [y/N] "):
print("Aborted.")
return
- deleted, routing_deleted, skipped = db.prune_never_active_keyed_sessions(
- older_than_days=days, sessions_dir=_sessions_dir()
- )
+ owner = getattr(args, "owner_endpoint", None)
+ if owner is not None:
+ from hermes_cli.gateway_client import GatewayClientError
+ from hermes_cli.sessions_owner import owner_prune, report_owner_failure
+ try:
+ result = owner_prune(owner, never_active_days=days)
+ except (GatewayClientError, OSError, TimeoutError) as exc:
+ return report_owner_failure(exc)
+ deleted, routing_deleted, skipped = result["deleted"], result["routing_deleted"], result["skipped"]
+ else:
+ deleted, routing_deleted, skipped = db.prune_never_active_keyed_sessions(
+ older_than_days=days, sessions_dir=_sessions_dir()
+ )
print(f"Deleted {deleted} never-active session(s) and {routing_deleted} stale routing entr(ies).")
if skipped:
print(f"Skipped {skipped} session(s) with a live turn or compression lock.")
@@ -753,7 +763,15 @@ def _cmd_prune_or_archive(db, args, action):
if not args.yes and not _confirm_prompt(f"{verb} these {len(candidates)} session(s) ({_span})? [y/N] "):
print("Cancelled.")
return
- if prune:
+ if prune and getattr(args, "owner_endpoint", None) is not None:
+ # The live gateway owns the store: it deletes, through the housekeeping retirement path.
+ from hermes_cli.gateway_client import GatewayClientError
+ from hermes_cli.sessions_owner import owner_prune, report_owner_failure
+ try:
+ print(f"Pruned {owner_prune(args.owner_endpoint, filters=filters)['deleted']} session(s).")
+ except (GatewayClientError, OSError, TimeoutError) as exc:
+ return report_owner_failure(exc)
+ elif prune:
print(f"Pruned {db.prune_sessions(sessions_dir=_sessions_dir(), exclude_active_write_guards=True, **filters)} session(s).")
else:
print(f"Archived {db.archive_sessions(**filters)} session(s). They're hidden from listings "
@@ -1236,6 +1254,12 @@ def cmd_sessions(args, sessions_parser=None):
and getattr(args, "format", None) in ("md", "qmd")
)
observational = action in _OBSERVATIONAL_DB_ACTIONS or (action == "export" and not deleting_export)
+ if action == "prune":
+ # The always-on gateway owns the store: this process only reads the preview, the owner
+ # deletes. No gateway: the local prune below, behind the holder scan, as before.
+ from hermes_cli.sessions_owner import live_owner
+ args.owner_endpoint = live_owner()
+ observational = args.owner_endpoint is not None
# A served-profile process has no single default home: pass the store path explicitly.
path = get_hermes_home() / "state.db"
try:
@@ -1253,7 +1277,8 @@ def cmd_sessions(args, sessions_parser=None):
if handler is None:
sessions_parser.print_help()
return
- if action in _HELD_STORE_ACTIONS and not getattr(args, "dry_run", False) and not getattr(args, "force", False):
+ if (action in _HELD_STORE_ACTIONS and not getattr(args, "dry_run", False) and not getattr(args, "force", False)
+ and getattr(args, "owner_endpoint", None) is None):
from hermes_state_holders import held_store_refusal
# Same path the SessionDB above opened, so the scan never depends on the db object.
refusal = held_store_refusal(path, command=action)
diff --git a/hermes_cli/sessions_owner.py b/hermes_cli/sessions_owner.py
new file mode 100644
index 00000000000..30da37710c2
--- /dev/null
+++ b/hermes_cli/sessions_owner.py
@@ -0,0 +1,38 @@
+"""Bulk prune while the gateway is up: the owner applies it, this process never writes.
+
+The one always-on gateway owns ``state.db``; a CLI rewriting it underneath is the second writer
+the held-store refusal exists to stop. So when a ready owner serves this home, ``hermes sessions
+prune`` reads its preview from a read-only view and sends the selected filters to the owner
+(``session.prune``), which deletes through the same ``retire_prunable`` path housekeeping uses.
+With no gateway, prune stays the local command it always was (holder scan, ``--force``).
+"""
+from __future__ import annotations
+
+#: A cron-heavy store prunes tens of thousands of rows in one transaction; the owner shields the
+#: write, so a short client budget would only misreport a prune that still commits.
+PRUNE_RPC_TIMEOUT = 600
+
+
+def live_owner():
+ """The ready gateway endpoint serving this home, else None. Discovery only: never starts one."""
+ from hermes_cli.gateway_runtime import discover_gateway_endpoint
+ from hermes_constants import get_hermes_home
+ found = discover_gateway_endpoint(get_hermes_home().resolve())
+ return found.endpoint if found.state == "ready" else None
+
+
+def owner_prune(endpoint, **params) -> dict:
+ """Run one ``session.prune`` on *endpoint*; raises ``GatewayClientError`` on refusal/loss."""
+ import asyncio
+ from hermes_cli.gateway_client import connect_gateway
+
+ async def _run():
+ async with connect_gateway(endpoint) as client:
+ return await client.rpc("session.prune", _timeout=PRUNE_RPC_TIMEOUT, **params)
+ return asyncio.run(_run())
+
+
+def report_owner_failure(exc) -> int:
+ print(f"Error: the gateway did not complete the prune ({exc}). Run `hermes sessions prune --dry-run` "
+ "with the same filters to see what is left.")
+ return 1
diff --git a/hermes_cli/subcommands/sessions.py b/hermes_cli/subcommands/sessions.py
index b798a85321f..0ee906334fe 100644
--- a/hermes_cli/subcommands/sessions.py
+++ b/hermes_cli/subcommands/sessions.py
@@ -128,7 +128,7 @@ def build_sessions_parser(subparsers, *, cmd_sessions: Callable) -> None:
"and are older than AGE (default 30 days). Ordinary prune can "
"never reach these — it only ever selects ended sessions")
_flag(sessions_prune, "--force",
- help="Run even while another Hermes process (gateway, Desktop, dashboard, cron) holds state.db — rewriting the store under a live writer can leave every agent refusing turns until all writers are stopped")
+ help="With no gateway running: run even while another Hermes process (Desktop, dashboard, cron) holds state.db — rewriting the store under a live writer can leave every agent refusing turns until all writers are stopped. With the gateway running, prune always goes through it")
sessions_archive = sessions_subparsers.add_parser(
"archive", help="Bulk-archive (soft-hide) sessions matching filters — no deletion")
diff --git a/hermes_state_gateway.py b/hermes_state_gateway.py
index 198add1df34..b7ac2326cbb 100644
--- a/hermes_state_gateway.py
+++ b/hermes_state_gateway.py
@@ -404,7 +404,8 @@ class SessionGatewayMixin:
return len(doomed)
def prune_never_active_keyed_sessions(
- self, *, older_than_days: float, sessions_dir: Optional[Path] = None) -> tuple[int, int, int]:
+ self, *, older_than_days: float, sessions_dir: Optional[Path] = None,
+ deleted_ids: Optional[list] = None) -> tuple[int, int, int]:
"""Delete never-active keyed rows and the routing entries naming them; returns
``(sessions_deleted, routing_entries_deleted, sessions_skipped)``. Deletion goes through
:meth:`delete_sessions` (one transaction; delegate cascade, FTS, transcripts).
@@ -415,7 +416,8 @@ class SessionGatewayMixin:
candidate except the guarded ones: rows that vanished concurrently are gone too,
and a stale entry outliving its target would have the gateway resume a
nonexistent id. The row sweep is one transaction; routing entries are dropped in a
- second write after it commits. ``sessions_skipped`` counts only the guarded rows."""
+ second write after it commits. ``sessions_skipped`` counts only the guarded rows.
+ ``deleted_ids`` (the owning gateway) receives every candidate id that was not kept."""
candidates = self.list_never_active_keyed_sessions(older_than_days=older_than_days)
if not candidates:
return (0, 0, 0)
@@ -430,6 +432,8 @@ class SessionGatewayMixin:
kept = set(skipped)
self._delete_routing_entries_for_sessions(ids - kept)
routing_deleted = sum(1 for _, _, sid in routed_before if sid not in kept)
+ if deleted_ids is not None:
+ deleted_ids.extend(sorted(ids - kept))
return (deleted, routing_deleted, len(skipped))
def list_gateway_sessions(
diff --git a/hermes_state_maintenance.py b/hermes_state_maintenance.py
index d1bb68447c9..5ff02f2bd1a 100644
--- a/hermes_state_maintenance.py
+++ b/hermes_state_maintenance.py
@@ -325,14 +325,16 @@ class SessionMaintenanceMixin:
def prune_sessions(self, older_than_days: Optional[float] = 90, source: str | None = None,
sessions_dir: Optional[Path] = None, exclude_active_write_guards: bool = False,
- **filters) -> int:
+ deleted_ids: Optional[list] = None, **filters) -> int:
"""Delete ended sessions inactive for ``older_than_days`` (an explicit ``started_before`` /
``last_active_before`` overrides it; None = no implicit bound) matching the filters.
Children outside the window are orphaned (parent NULLed), not cascade-deleted. With
*sessions_dir*, transcript files are removed outside the DB transaction.
``exclude_active_write_guards`` (automatic maintenance) skips rows under a live turn lease
or compression lock while expired/dead holders are reclaimed and fenced. A compression
- ancestor is deleted only together with every continuation after it (``whole_lineages``)."""
+ ancestor is deleted only together with every continuation after it (``whole_lineages``).
+ ``deleted_ids`` (the owning gateway) receives the removed ids, so it can retire their
+ in-memory routes and live sessions after the commit."""
where, where_params = self._prune_where(older_than_days, source, filters, whole_lineages=True)
removed_ids: list[str] = []
def _do(conn):
@@ -358,6 +360,8 @@ class SessionMaintenanceMixin:
collect_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)
return count
def _page_pragmas(self, names: tuple[str, ...], fail_msg: str) -> Optional[list]:
diff --git a/tests/hermes_cli/test_sessions_prune_via_owner.py b/tests/hermes_cli/test_sessions_prune_via_owner.py
new file mode 100644
index 00000000000..e390176b7ab
--- /dev/null
+++ b/tests/hermes_cli/test_sessions_prune_via_owner.py
@@ -0,0 +1,137 @@
+"""`hermes sessions prune` while the always-on gateway owns state.db (live smoke LS-F7).
+
+The gateway is always up, so a CLI prune that refuses whenever a process holds the store (and
+deletes under it with ``--force``) is unusable or a second writer. With a ready owner the CLI only
+reads its preview; the owner deletes through ``session.prune`` with the housekeeping retirement
+path, which keeps a retained reset child's logical owner. A REAL foreign process holds the store,
+as the gateway does; the owner end is the production ``AuthorityConnection`` dispatch.
+"""
+import subprocess
+import sys
+import time
+from argparse import Namespace
+from contextlib import asynccontextmanager, closing
+from types import SimpleNamespace
+
+import pytest
+
+import hermes_state_runtime as rt
+from gateway.session_authority import LiveSession, SessionAuthority
+from gateway.session_controls import AuthorityConnection
+from hermes_cli import sessions_cmd
+from hermes_state import SessionDB
+from tests.hermes_state.test_target_advance_fence import _local_session, _mutate
+
+pytestmark = pytest.mark.platforms("posix") # the holder scan the old path refused on is POSIX-only
+
+_HOLDER = ("import sqlite3, sys\nconn = sqlite3.connect(sys.argv[1])\n"
+ "conn.execute('SELECT count(*) FROM sqlite_master')\nprint('ready', flush=True)\nsys.stdin.readline()\n")
+
+
+def _aged(db, sid, days, *, ended=True):
+ at = time.time() - days * 86400
+
+ def write(conn): # last activity = freshest of row activity and the latest message
+ conn.execute('UPDATE sessions SET started_at=?, last_activity_at=?, ended_at=? WHERE id=?',
+ (at, at, at if ended else None, sid))
+ conn.execute('UPDATE messages SET timestamp=? WHERE session_id=?', (at, sid))
+ db._execute_write(write)
+
+
+def _connection(authority, *, operator, native=True):
+ identity = {'user_id': 'local-operator', 'provider': 'local', 'profile_id': authority.profile_id,
+ 'instance_id': authority.instance_id, 'native_bootstrap': native,
+ 'capabilities': ['session:create', 'session:read', 'session:submit', 'session:control']}
+ return AuthorityConnection(authority, object(), identity, operator=operator)
+
+
+def owned_store(monkeypatch, tmp_path):
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ db = SessionDB(db_path=tmp_path / 'state.db')
+ epoch = rt.begin_runtime_epoch(db, instance_id='owner')
+ retired = []
+ runner = SimpleNamespace(_draining=False, session_store=SimpleNamespace(retire_runtime_sessions=retired.extend))
+ authority = SessionAuthority(runner, profile_id=str(tmp_path), instance_id='owner', db=db, epoch=epoch)
+ owner = _local_session(db, epoch, tmp_path)
+ child = _mutate(db, epoch, owner, 'reset')['target_session_id'] # ends `owner`, keeps it as the FIFO owner
+ db.append_message(child, 'user', 'kept turn')
+ _aged(db, owner, 200)
+ for sid, source, days in (('old-cli', 'cli', 200), ('old-cron', 'cron', 200), ('fresh-cli', 'cli', 1)):
+ db.create_session(sid, source)
+ db.append_message(sid, 'user', sid)
+ _aged(db, sid, days)
+ authority.sessions['old-cli'] = LiveSession(None, 'route-old-cli') # resident in owner memory
+ with closing(db):
+ yield SimpleNamespace(db=db, authority=authority, owner=owner, child=child, retired=retired,
+ path=tmp_path / 'state.db')
+
+
+def test_prune_under_the_live_owner_is_applied_by_the_owner_not_refused(owned_store, monkeypatch, capsys):
+ from hermes_cli import gateway_client
+ from hermes_cli import gateway_runtime
+ import hermes_state
+ from hermes_cli.gateway_client import rpc_error
+ store = owned_store
+ holder = subprocess.Popen([sys.executable, '-c', _HOLDER, str(store.path)],
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
+ assert holder.stdout.readline().strip() == 'ready'
+ opened = []
+ real_db = hermes_state.SessionDB
+
+ def recording_db(*args, **kwargs):
+ opened.append(kwargs.get('read_only', False))
+ return real_db(*args, **kwargs)
+
+ @asynccontextmanager
+ async def owner_socket(*_args, **_kwargs):
+ connection = _connection(store.authority, operator=True)
+
+ async def rpc(method, _timeout=None, **params):
+ frame = await connection.dispatch({'id': 1, 'method': method, 'params': params})
+ if 'error' in frame:
+ raise rpc_error(frame['error'])
+ return frame['result']
+ try:
+ yield SimpleNamespace(rpc=rpc)
+ finally:
+ await connection.close()
+
+ monkeypatch.setattr(gateway_runtime, 'discover_gateway_endpoint',
+ lambda home, **_: gateway_runtime.GatewayDiscovery('ready', endpoint=object()))
+ monkeypatch.setattr(gateway_client, 'connect_gateway', owner_socket)
+ monkeypatch.setattr(hermes_state, 'SessionDB', recording_db)
+ args = Namespace(sessions_action='prune', dry_run=False, yes=True, force=False, never_active=False,
+ include_archived=False, include_pinned=False,
+ **{name: None for name in sessions_cmd._FILTER_ARGS})
+ args.older_than = '90'
+ try:
+ assert sessions_cmd.cmd_sessions(args) in (None, 0)
+ finally:
+ holder.stdin.close()
+ holder.wait(timeout=10)
+ out = capsys.readouterr().out
+ assert 'Refusing' not in out and 'Pruned 2 session(s).' in out, out
+ db = store.db
+ # --older-than honoured; the retained reset child's logical owner and its history survive.
+ assert db.get_session('old-cli') is None and db.get_session('old-cron') is None
+ assert db.get_session('fresh-cli') is not None and db.get_session(store.owner) is not None
+ assert [m['content'] for m in db.get_messages(store.child)] == ['kept turn']
+ # The CLI never opened a writer; the owner retired the deleted ids from its own memory too.
+ assert opened == [True], opened
+ assert 'old-cli' not in store.authority.sessions and set(store.retired) == {'old-cli', 'old-cron'}
+
+
[email protected]('grant', ['viewer', 'remote_operator'])
+async def test_owner_prune_is_local_operator_only(owned_store, grant):
+ """Store-wide deletion across every principal's rows: only the native local operator ticket."""
+ connection = _connection(owned_store.authority, operator=grant == 'remote_operator',
+ native=grant != 'remote_operator')
+ try:
+ refused = await connection.dispatch({'id': 1, 'method': 'session.prune',
+ 'params': {'filters': {'older_than_days': 0}}})
+ finally:
+ await connection.close()
+ assert refused['error']['message'] == 'permission_denied', refused
+ assert owned_store.db.get_session('old-cli') is not None
diff --git a/tui_gateway/contracts/canonical.py b/tui_gateway/contracts/canonical.py
index 5c58351c28e..1241a4bd47e 100644
--- a/tui_gateway/contracts/canonical.py
+++ b/tui_gateway/contracts/canonical.py
@@ -104,6 +104,25 @@ canonical_method("session.mutate", params=SessionMutateParams, result=SessionMut
"delete, rewind, reset, model, compress, import).")
+class SessionPruneParams(Params):
+ """Exactly one of ``filters`` (``SessionDB.prune_sessions`` keyword filters, as
+ ``hermes sessions prune`` builds them) or ``never_active_days`` (``--never-active``)."""
+
+ filters: dict[str, JsonValue] | None = None
+ never_active_days: float | None = None
+
+
+class SessionPruneResult(Result):
+ deleted: int
+ routing_deleted: int | None = None
+ skipped: int | None = None
+
+
+canonical_method("session.prune", params=SessionPruneParams, result=SessionPruneResult,
+ doc="Local operator only: the owner deletes the ended sessions `hermes sessions prune` "
+ "selected, skipping busy sessions and retained reset owners.")
+
+
class CanonicalSessionInfoParams(Params):
session_id: str
@@ -370,4 +389,4 @@ canonical_method("groups.discard", params=GroupsDiscardParams, result=GroupsDisc
# Shared-name overrides load after the authority-only value shapes above.
-from . import canonical_sessions, canonical_projections # noqa: F401,E402
+from . import canonical_sessions, canonical_projections
diff --git a/website/docs/user-guide/session-storage-recovery.md b/website/docs/user-guide/session-storage-recovery.md
index aa1e522f3f7..ff545834a63 100644
--- a/website/docs/user-guide/session-storage-recovery.md
+++ b/website/docs/user-guide/session-storage-recovery.md
@@ -80,6 +80,11 @@ Override with --force if you accept the risk.
the listed processes are idle (a reader you started yourself, for example). The same check
runs when you type `sessions optimize` in the Desktop console.
+`hermes sessions prune` is the exception while the gateway is running: the gateway owns
+`state.db`, so prune shows its preview from a read-only view and the gateway itself deletes
+the selected sessions (skipping any with a turn still running). It refuses as above only when
+no gateway is running and some other process holds the database.
+
## Files you may find beside `state.db`
| File or directory | What it is | What to do |
diff --git a/website/docs/user-guide/sessions.md b/website/docs/user-guide/sessions.md
index 0ea911a9ff5..b1bb98c423b 100644
--- a/website/docs/user-guide/sessions.md
+++ b/website/docs/user-guide/sessions.md
@@ -98,9 +98,10 @@ Use `/compress` when a session gets long, `/new` for a fresh thread, and
`hermes sessions prune` only when you want to delete old ended sessions from
storage. If `state.db` has simply grown large, start with the non-destructive
option first: `hermes sessions optimize` merges FTS5 index segments and
-VACUUMs the database without touching any session data. Both `optimize` and `prune` refuse
-while another Hermes process (gateway, Desktop, dashboard, cron) holds `state.db` — stop it
-first, or pass `--force`; see [Session storage recovery](session-storage-recovery.md).
+VACUUMs the database without touching any session data. With the gateway running, `prune`
+asks the gateway to delete the sessions it selected. `optimize`, and `prune` with no gateway
+running, refuse while another Hermes process (Desktop, dashboard, cron) holds `state.db`. Stop
+it first, or pass `--force`; see [Session storage recovery](session-storage-recovery.md).
Compression reduces the active context; it is not a privacy delete.
Pass a name to `/new` (e.g. `/new payments-refactor`) to set the new session's
initial title up front — useful for finding it later with `/resume <name>` or