Files
hermes-agent/persistence/sqlite/_state/keys.py
yoniebans be3d6affc8 refactor(state)!: remove the old session store
hermes_state.py becomes the stand-in plugins import, the rest of the legacy store and its test folder go, and the per-process modules the backend imported from main move under persistence/sqlite/_state/. The backend checks PID namespaces and lease holders through process_identity and its WAL setup through sqlite_support, and its error module takes the shared predicates and classification from storage_errors, so neither helper set has a second copy. The backend, sqlite_support.py and the tests that pin those modules reach their final imports, and the backend-import guard allows no file outside persistence/. The modules no caller imports any more go with it: the agent's onboarding rules (now in session_rules) and gateway/session_admission.py.

The stand-in's SessionDB releases its store on close() and, used again afterwards, opens it again with a warning, as the old class reopened its connection, unless the file at its path was replaced or the store is latched corrupt; a read-only one raises. A close during a call releases the store when the call returns. A named source wins over a source list in its session listing and count.

An agent given a writable stand-in SessionDB as session_db= and no persistence= takes the store handle that SessionDB forwards to as its persistence, so its turn flush, token counts, compression and session row writes go through the storage interface, as an agent given the old SessionDB wrote through it.

The backend-import guard also holds the backend's remaining reads of the process or task home, each with its reason, and refuses any other and any import of the stand-in inside persistence/sqlite/.

Plugin context engines get the agent's store as persistence= beside the deprecated session_db=, in each hook whose signature accepts that keyword, including the rebind after /new, /resume and /branch, and the context engine guide and the plugin guide's replacement table name it. A test fails once the running release reaches the stand-in's removal release, listing what goes with the stand-in.

release_unheld_media and collect_unheld_api_images take a store only: their SessionDB branches, which no caller reaches, go with the gateway's own copies of the admission and transcript queries.
2026-11-17 19:10:57 +01:00

92 lines
4.0 KiB
Python

"""Pure identity derivations the canonical store and the gateway both need.
stdlib-only on purpose: the store must not import ``gateway/`` to compute a digest or parse a key
(the gateway imports the store, so the reverse edge is a latent cycle).
"""
import hashlib
import json
import re
# The profile scheduler's principal admits every cron fire under ``cron:<job>:<execution>``
# (``gateway/session_cron.py``). That request id is the pre-image of the run's ``local-*`` session
# id, so its admission row is the run's durable job/execution association. Runs from before the
# unified runtime were named ``cron_{job_id}_{YYYYmmdd_HHMMSS}`` (``cron/scheduler.py::run_job``).
CRON_PRINCIPAL_ID = 'cron-owner'
CRON_REQUEST_PREFIX = 'cron:'
_LEGACY_CRON_RUN_ID = re.compile(r'^cron_(.+)_\d{8}_\d{6}$')
def cron_request_id(job_id, execution_id):
"""The admission request id of one cron fire (``execution_id`` is its ledger row id)."""
return f'{CRON_REQUEST_PREFIX}{job_id}:{execution_id}'
def prefix_range(prefix):
"""Half-open ``[prefix, hi)`` bounds of every key starting with *prefix*, for an index range
scan: bump the final character so the range covers exactly the prefix."""
return prefix, prefix[:-1] + chr(ord(prefix[-1]) + 1)
def cron_request_range(job_id):
"""Half-open ``[lo, hi)`` bounds of *job_id*'s cron request ids, for an index range scan."""
return prefix_range(cron_request_id(job_id, ''))
def cron_run_from_request(request_id, job_id=None):
"""``(job_id, execution_id)`` of a cron fire's request id, else None.
A fresh fire's execution id never holds ``:``, so a request id with exactly one after the
prefix splits there. More than one is ambiguous (a job id holding ``:``, or an execution id
admitted with one before that was refused): only the *job_id* its stored policy names splits
it, and must prefix it."""
if not isinstance(request_id, str) or not request_id.startswith(CRON_REQUEST_PREFIX):
return None
if job_id is None:
rest = request_id[len(CRON_REQUEST_PREFIX):]
if rest.count(':') != 1:
return None
job_id, _, execution_id = rest.partition(':')
else:
prefix = cron_request_id(job_id, '')
execution_id = request_id[len(prefix):] if request_id.startswith(prefix) else ''
return (job_id, execution_id) if job_id and execution_id else None
def legacy_cron_run_job(session_id):
"""The job id a pre-unified ``cron_{job_id}_{YYYYmmdd_HHMMSS}`` run session names, else None."""
match = _LEGACY_CRON_RUN_ID.match(str(session_id or ''))
return match.group(1) if match else None
def admission_fingerprint(*, canonical_target: str, payload: dict) -> str:
"""Canonical payload identity after authorization and immutable media capture."""
encoded = json.dumps(
{'target': canonical_target, 'payload': payload}, ensure_ascii=False,
sort_keys=True, separators=(',', ':'), allow_nan=False,
).encode('utf-8', errors='surrogatepass')
return hashlib.sha256(encoded).hexdigest()
def local_identity(profile_id, principal_id, request_id):
"""The deterministic session id of a LOCAL creation receipt."""
identity = json.dumps([profile_id, principal_id, request_id], separators=(',', ':'))
return 'local-' + hashlib.sha256(identity.encode()).hexdigest()
def profile_from_session_key_namespace(namespace: str) -> str:
"""Inverse of ``gateway.session._session_key_namespace`` for the ``<ns>`` slot of a key:
``"default"`` for ``main``, ``"main"`` for the marked ``main~``, else the slot is the profile id."""
if namespace == "main":
return "default"
return "main" if namespace == "main~" else namespace
def profile_from_session_key(session_key):
"""Profile namespace encoded in an ``agent:<ns>:...`` gateway session key, else None."""
if not session_key:
return None
parts = str(session_key).split(":")
if len(parts) < 2 or parts[0] != "agent":
return None
return profile_from_session_key_namespace(parts[1] or "main")