Skip to content

The agent that grows with you

refactor(state): keep storage identity helpers out of gateway/

Teknium7ee588ea4c1d
diff --git a/gateway/session.py b/gateway/session.py
index 3a720f87eb7..e4d43246425 100644
--- a/gateway/session.py
+++ b/gateway/session.py
@@ -20,6 +20,8 @@ from gateway.session_prompt_pin import SessionPromptPinMixin, sanitize_prompt_pi
from gateway.session_recovery import SessionRecoveryMixin
from gateway.session_lifecycle import SessionLifecycleMixin, _iso, _new_session_id, _now, _parse_iso
from gateway.session_transcript import SessionTranscriptMixin
+# Inverse of _session_key_namespace, defined storage-side (hermes_state must not import gateway).
+from hermes_state_keys import profile_from_session_key_namespace # noqa: F401
logger = logging.getLogger(__name__)
@@ -665,14 +667,6 @@ def _session_key_namespace(profile: Optional[str]) -> str:
return "agent:main~" if profile == "main" else f"agent:{profile}"
-def profile_from_session_key_namespace(namespace: str) -> str:
- """Inverse of :func:`_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 _canonical_participant(source: SessionSource) -> Optional[str]:
"""Sender id for key isolation; WhatsApp JID/LID aliases are canonicalized so alias flips
cannot split one member into two sessions."""
diff --git a/gateway/session_admission.py b/gateway/session_admission.py
index cee4225181b..04c175a4b8f 100644
--- a/gateway/session_admission.py
+++ b/gateway/session_admission.py
@@ -1,11 +1,8 @@
-"""Canonical payload identity after authorization and immutable media capture."""
-import hashlib
-import json
+"""Canonical payload identity after authorization and immutable media capture.
+The digest is defined storage-side (``hermes_state_keys``) so the canonical store never imports
+``gateway/``; this module keeps the gateway-facing name.
+"""
+from hermes_state_keys import admission_fingerprint
-def admission_fingerprint(*, canonical_target: str, payload: dict) -> str:
- 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()
+__all__ = ['admission_fingerprint']
diff --git a/gateway/session_local_recovery.py b/gateway/session_local_recovery.py
index 8fecb9aa48d..09cd7ff6a02 100644
--- a/gateway/session_local_recovery.py
+++ b/gateway/session_local_recovery.py
@@ -1,21 +1,15 @@
"""Restore only private, profile-bound local policy into the existing authority."""
-import hashlib
-import json
import logging
from pathlib import Path
from gateway.config import Platform
from gateway.session import SessionEntry, SessionSource
from gateway.session_contract import SessionRef
+from hermes_state_keys import local_identity
from hermes_state_local import POLICY_PREFIX, local_receipt
from hermes_state_runtime import RuntimeStoreError, list_session_admissions
-def local_identity(profile_id, principal_id, request_id):
- identity = json.dumps([profile_id, principal_id, request_id], separators=(',', ':'))
- return 'local-' + hashlib.sha256(identity.encode()).hexdigest()
-
-
def local_adapter_map(authority):
"""The adapter map a LOCAL session of *authority* lives in: ``runner.adapters`` for the launch
profile, ``runner._profile_adapters[name]`` for a served secondary (its routed home, so
diff --git a/gateway/session_recovery.py b/gateway/session_recovery.py
index 83c4f25206f..2e6173af5e3 100644
--- a/gateway/session_recovery.py
+++ b/gateway/session_recovery.py
@@ -54,13 +54,8 @@ class SessionRecoveryMixin:
@staticmethod
def _profile_from_session_key(session_key: Optional[str]) -> Optional[str]:
"""Extract the profile namespace encoded in a gateway session key."""
- if not session_key:
- return None
- parts = str(session_key).split(":")
- if len(parts) < 2 or parts[0] != "agent":
- return None
- from gateway.session import profile_from_session_key_namespace
- return profile_from_session_key_namespace(parts[1] or "main")
+ from hermes_state_keys import profile_from_session_key
+ return profile_from_session_key(session_key)
@staticmethod
def _active_profile_name() -> str:
diff --git a/hermes_state_keys.py b/hermes_state_keys.py
new file mode 100644
index 00000000000..3fdddb71098
--- /dev/null
+++ b/hermes_state_keys.py
@@ -0,0 +1,41 @@
+"""Pure identity derivations the canonical store and the gateway both need.
+
+stdlib-only on purpose: ``hermes_state_*`` modules 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).
+The gateway modules that historically defined these re-export them from here.
+"""
+import hashlib
+import json
+
+
+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")
diff --git a/hermes_state_local_lineage.py b/hermes_state_local_lineage.py
index 768ee4bed93..197d7edbdf0 100644
--- a/hermes_state_local_lineage.py
+++ b/hermes_state_local_lineage.py
@@ -12,7 +12,7 @@ from hermes_state_runtime import RuntimeStoreError, _epoch, _json
def validate_local_lineage(conn, receipt):
from hermes_state_compression import _CHAIN_STEP_SQL
- from gateway.session_local_recovery import local_identity
+ from hermes_state_keys import local_identity
if ('legacy_session_id' not in receipt and
receipt['session_id'] != local_identity(receipt['profile_id'], receipt['principal_id'], receipt['request_id'])):
raise RuntimeStoreError('storage_unavailable')
diff --git a/hermes_state_mutation_branch.py b/hermes_state_mutation_branch.py
index 284036085ea..4ebd9d935b7 100644
--- a/hermes_state_mutation_branch.py
+++ b/hermes_state_mutation_branch.py
@@ -17,14 +17,15 @@ def branch_in_transaction(db, conn, session_id, payload):
saved = json.loads(row[0])
target = validate_local_lineage(conn, saved)
require_idle(db, conn, list({session_id, target}))
+ # Late: the routing entry/key are gateway types (the gateway imports this store at module level).
from gateway.session import SessionEntry, SessionSource
from gateway.config import Platform
- from gateway.session_local_recovery import local_identity
+ from hermes_state_keys import local_identity, profile_from_session_key
request_id = 'branch:' + uuid.uuid4().hex
child = local_identity(saved['profile_id'], saved['principal_id'], request_id)
source = SessionSource(Platform.LOCAL, child, user_id=saved['principal_id'], chat_type='dm')
- from gateway.session import build_session_key, SessionStore
- route = build_session_key(source, profile=SessionStore._profile_from_session_key(saved['route']))
+ from gateway.session import build_session_key
+ route = build_session_key(source, profile=profile_from_session_key(saved['route']))
from gateway.session_lifecycle import _now
now = _now()
entry = SessionEntry(route, child, now, now, origin=source, platform=Platform.LOCAL)
diff --git a/hermes_state_profile_repair.py b/hermes_state_profile_repair.py
index 225bb76a934..04b681ae752 100644
--- a/hermes_state_profile_repair.py
+++ b/hermes_state_profile_repair.py
@@ -37,7 +37,7 @@ def session_key_profile(session_key: Any) -> Optional[str]:
parts = session_key.split(":")
if len(parts) < 3 or parts[0] != "agent" or not parts[1]:
return None
- from gateway.session import profile_from_session_key_namespace
+ from hermes_state_keys import profile_from_session_key_namespace
return profile_from_session_key_namespace(parts[1])
diff --git a/hermes_state_runtime.py b/hermes_state_runtime.py
index f43ecea1a5b..47c6c266533 100644
--- a/hermes_state_runtime.py
+++ b/hermes_state_runtime.py
@@ -8,7 +8,7 @@ import uuid
from agent.conversation_compression_archive import ABSORBED_ROW_IDS
from agent.message_metadata import CANONICAL_ROW, DB_ROW_SNAPSHOT, PERSISTENCE_ONLY_MESSAGE_FIELDS
-from gateway.session_admission import admission_fingerprint
+from hermes_state_keys import admission_fingerprint
class RuntimeStoreError(ValueError):
diff --git a/hermes_state_worker_compression.py b/hermes_state_worker_compression.py
index c8040f31766..02386552d5f 100644
--- a/hermes_state_worker_compression.py
+++ b/hermes_state_worker_compression.py
@@ -367,7 +367,7 @@ def worker_claim_origin(db, params):
def worker_retry_target(db, params):
"""Transport verification accepts old targets only for exact publication replay."""
- from gateway.session_admission import admission_fingerprint
+ from hermes_state_keys import admission_fingerprint
if params.get('operation') != 'compression.publish':
return params['session_id']
digest = admission_fingerprint(canonical_target=params['session_id'],
diff --git a/tests/hermes_state/test_storage_import_boundary.py b/tests/hermes_state/test_storage_import_boundary.py
new file mode 100644
index 00000000000..1e3f9954413
--- /dev/null
+++ b/tests/hermes_state/test_storage_import_boundary.py
@@ -0,0 +1,24 @@
+"""The canonical store must not import gateway/ to compute its own identities (latent cycle)."""
+import subprocess
+import sys
+
+
+def test_runtime_storage_modules_import_without_loading_gateway():
+ probe = ("import sys, hermes_state, hermes_state_runtime, hermes_state_local, hermes_state_local_lineage, "
+ "hermes_state_mutation_branch, hermes_state_mutations, hermes_state_worker_compression; "
+ "print(sorted(m for m in sys.modules if m == 'gateway' or m.startswith('gateway.')))")
+ out = subprocess.run([sys.executable, '-c', probe], capture_output=True, text=True, check=True)
+ assert out.stdout.strip() == '[]', out.stdout
+
+
+def test_gateway_names_are_the_storage_definitions():
+ import hermes_state_keys as keys
+ from gateway.session import SessionStore, profile_from_session_key_namespace
+ from gateway.session_admission import admission_fingerprint
+ from gateway.session_local_recovery import local_identity
+ assert admission_fingerprint is keys.admission_fingerprint
+ assert local_identity is keys.local_identity
+ assert profile_from_session_key_namespace is keys.profile_from_session_key_namespace
+ for key, profile in (('agent:main:local:dm:x', 'default'), ('agent:main~:local:dm:x', 'main'),
+ ('agent:work:local:dm:x', 'work'), ('agent::x', 'default'), ('cli:x', None), (None, None)):
+ assert SessionStore._profile_from_session_key(key) == keys.profile_from_session_key(key) == profile