hermes_state_keys.py 4.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. """Pure identity derivations the canonical store and the gateway both need.
  2. stdlib-only on purpose: ``hermes_state_*`` modules must not import ``gateway/`` to compute a
  3. digest or parse a key (the gateway imports the store, so the reverse edge is a latent cycle).
  4. The gateway modules that historically defined these re-export them from here.
  5. """
  6. import hashlib
  7. import json
  8. import re
  9. # The profile scheduler's principal admits every cron fire under ``cron:<job>:<execution>``
  10. # (``gateway/session_cron.py``). That request id is the pre-image of the run's ``local-*`` session
  11. # id, so its admission row is the run's durable job/execution association. Runs from before the
  12. # unified runtime were named ``cron_{job_id}_{YYYYmmdd_HHMMSS}`` (``cron/scheduler.py::run_job``).
  13. CRON_PRINCIPAL_ID = 'cron-owner'
  14. CRON_REQUEST_PREFIX = 'cron:'
  15. _LEGACY_CRON_RUN_ID = re.compile(r'^cron_(.+)_\d{8}_\d{6}$')
  16. def cron_request_id(job_id, execution_id):
  17. """The admission request id of one cron fire (``execution_id`` is its ledger row id)."""
  18. return f'{CRON_REQUEST_PREFIX}{job_id}:{execution_id}'
  19. def prefix_range(prefix):
  20. """Half-open ``[prefix, hi)`` bounds of every key starting with *prefix*, for an index range
  21. scan: bump the final character so the range covers exactly the prefix."""
  22. return prefix, prefix[:-1] + chr(ord(prefix[-1]) + 1)
  23. def cron_request_range(job_id):
  24. """Half-open ``[lo, hi)`` bounds of *job_id*'s cron request ids, for an index range scan."""
  25. return prefix_range(cron_request_id(job_id, ''))
  26. def cron_run_from_request(request_id, job_id=None):
  27. """``(job_id, execution_id)`` of a cron fire's request id, else None.
  28. A fresh fire's execution id never holds ``:``, so a request id with exactly one after the
  29. prefix splits there. More than one is ambiguous (a job id holding ``:``, or an execution id
  30. admitted with one before that was refused): only the *job_id* its stored policy names splits
  31. it, and must prefix it."""
  32. if not isinstance(request_id, str) or not request_id.startswith(CRON_REQUEST_PREFIX):
  33. return None
  34. if job_id is None:
  35. rest = request_id[len(CRON_REQUEST_PREFIX):]
  36. if rest.count(':') != 1:
  37. return None
  38. job_id, _, execution_id = rest.partition(':')
  39. else:
  40. prefix = cron_request_id(job_id, '')
  41. execution_id = request_id[len(prefix):] if request_id.startswith(prefix) else ''
  42. return (job_id, execution_id) if job_id and execution_id else None
  43. def legacy_cron_run_job(session_id):
  44. """The job id a pre-unified ``cron_{job_id}_{YYYYmmdd_HHMMSS}`` run session names, else None."""
  45. match = _LEGACY_CRON_RUN_ID.match(str(session_id or ''))
  46. return match.group(1) if match else None
  47. def admission_fingerprint(*, canonical_target: str, payload: dict) -> str:
  48. """Canonical payload identity after authorization and immutable media capture."""
  49. encoded = json.dumps(
  50. {'target': canonical_target, 'payload': payload}, ensure_ascii=False,
  51. sort_keys=True, separators=(',', ':'), allow_nan=False,
  52. ).encode('utf-8', errors='surrogatepass')
  53. return hashlib.sha256(encoded).hexdigest()
  54. def local_identity(profile_id, principal_id, request_id):
  55. """The deterministic session id of a LOCAL creation receipt."""
  56. identity = json.dumps([profile_id, principal_id, request_id], separators=(',', ':'))
  57. return 'local-' + hashlib.sha256(identity.encode()).hexdigest()
  58. def profile_from_session_key_namespace(namespace: str) -> str:
  59. """Inverse of ``gateway.session._session_key_namespace`` for the ``<ns>`` slot of a key:
  60. ``"default"`` for ``main``, ``"main"`` for the marked ``main~``, else the slot is the profile id."""
  61. if namespace == "main":
  62. return "default"
  63. return "main" if namespace == "main~" else namespace
  64. def profile_from_session_key(session_key):
  65. """Profile namespace encoded in an ``agent:<ns>:...`` gateway session key, else None."""
  66. if not session_key:
  67. return None
  68. parts = str(session_key).split(":")
  69. if len(parts) < 2 or parts[0] != "agent":
  70. return None
  71. return profile_from_session_key_namespace(parts[1] or "main")