delegation_context.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. """Context-local state for delegate_task child execution.
  2. A Hermes process may itself be a Kanban dispatcher worker with HERMES_KANBAN_* in
  3. os.environ. In-process delegate_task children and cron jobs fired via
  4. ``cronjob(action="run")`` are NOT dispatcher-owned, so identity gates must fail
  5. closed for them without mutating the process-global environment.
  6. """
  7. from __future__ import annotations
  8. import os
  9. from contextlib import contextmanager
  10. from contextvars import ContextVar, Token
  11. from typing import Iterator, Mapping, MutableMapping, overload
  12. _DELEGATED_CHILD_CONTEXT: ContextVar[bool] = ContextVar("hermes_delegated_child_context", default=False)
  13. # Any in-process execution that is NOT the dispatcher-owned worker (cron jobs). Kept separate
  14. # so delegate_task-specific behaviour (subprocess env scrubbing, its error strings) is unchanged.
  15. _NON_DISPATCHER_OWNED_CONTEXT: ContextVar[bool] = ContextVar("hermes_non_dispatcher_owned_context", default=False)
  16. DELEGATED_CHILD_ENV_MARKER = "HERMES_DELEGATED_CHILD_CONTEXT"
  17. KANBAN_ENV_KEYS: tuple[str, ...] = (
  18. "HERMES_KANBAN_TASK", "HERMES_KANBAN_RUN_ID", "HERMES_KANBAN_CLAIM_LOCK",
  19. "HERMES_KANBAN_GOAL_MODE", "HERMES_KANBAN_GOAL_MAX_TURNS",
  20. )
  21. @contextmanager
  22. def delegated_child_context(session_id: str | None = None) -> Iterator[None]:
  23. """Mark child execution and isolate its task-local session identity. Even a context
  24. entered without an id must restore the parent's session ContextVar (child
  25. construction calls ``set_current_session_id``)."""
  26. token = _DELEGATED_CHILD_CONTEXT.set(True)
  27. try:
  28. from gateway.session_context import scoped_current_session_id # lazy: it calls is_delegated_child_context()
  29. with scoped_current_session_id(session_id):
  30. yield
  31. finally:
  32. _DELEGATED_CHILD_CONTEXT.reset(token)
  33. def is_delegated_child_context() -> bool:
  34. """Return True while code is running for a delegate_task child."""
  35. return bool(_DELEGATED_CHILD_CONTEXT.get())
  36. def enter_non_dispatcher_owned_context() -> Token[bool]:
  37. """Token form of :func:`non_dispatcher_owned_context` for long try/finally scopes."""
  38. return _NON_DISPATCHER_OWNED_CONTEXT.set(True)
  39. def exit_non_dispatcher_owned_context(token: Token[bool]) -> None:
  40. """Restore the flag saved by :func:`enter_non_dispatcher_owned_context`."""
  41. _NON_DISPATCHER_OWNED_CONTEXT.reset(token)
  42. @contextmanager
  43. def non_dispatcher_owned_context() -> Iterator[None]:
  44. """Mark in-process execution that does NOT own the dispatcher's Kanban task; without it
  45. a cron agent run inside a worker is misread as that worker (kanban toolset force-added,
  46. ``kanban_complete`` defaulting to its task). ContextVar-scoped rather than clearing
  47. os.environ, which the worker's claim heartbeat and concurrent readers share."""
  48. token = enter_non_dispatcher_owned_context()
  49. try:
  50. yield
  51. finally:
  52. exit_non_dispatcher_owned_context(token)
  53. def is_dispatcher_owned_worker_context() -> bool:
  54. """The single predicate every ``HERMES_KANBAN_*`` identity gate should use."""
  55. return not (is_delegated_child_process_context() or _NON_DISPATCHER_OWNED_CONTEXT.get())
  56. def explicit_board_intent_is_pinned() -> bool:
  57. """Whether an explicit kanban ``board=`` argument must still resolve through
  58. the dispatcher-injected env pins (``HERMES_KANBAN_DB`` & friends) rather than
  59. its own board directory.
  60. True for in-process delegate children, descendants carrying
  61. :data:`DELEGATED_CHILD_ENV_MARKER`, and dispatched workers
  62. (``HERMES_KANBAN_TASK`` set). The pins are the "workers physically cannot
  63. see other boards" isolation, and :func:`kanban_path_is_fenced` checks the
  64. pinned path / fenced root — an explicit board that resolved elsewhere would
  65. also escape that fence. Outside these fences an explicit board is the
  66. caller's own intent and wins.
  67. """
  68. if _DELEGATED_CHILD_CONTEXT.get():
  69. return True
  70. if os.environ.get(DELEGATED_CHILD_ENV_MARKER):
  71. return True
  72. return bool((os.environ.get("HERMES_KANBAN_TASK") or "").strip())
  73. def owned_kanban_task() -> str:
  74. """The board task this execution OWNS: ``HERMES_KANBAN_TASK`` for the dispatcher-owned
  75. worker, ``""`` otherwise. Tool access is not worker identity — a profile can expose the
  76. kanban toolset interactively, and children/cron runs inherit the env var — so every
  77. reader that turns the task id into worker behaviour (guidance, stop nudge, terminal
  78. outcomes) goes through this one helper."""
  79. if not is_dispatcher_owned_worker_context():
  80. return ""
  81. return (os.environ.get("HERMES_KANBAN_TASK") or "").strip()
  82. def is_delegated_child_process_context() -> bool:
  83. """Return True in this process or a subprocess spawned by a child."""
  84. return bool(_DELEGATED_CHILD_CONTEXT.get()) or bool(os.environ.get(DELEGATED_CHILD_ENV_MARKER))
  85. def _fenced_kanban_root() -> str:
  86. """The board root this process's Kanban lineage lives under (``kanban_home()``); ``"1"`` when it
  87. cannot be resolved, which readers treat as "fence every board" (the pre-path marker)."""
  88. try:
  89. from hermes_cli.kanban_db import kanban_home
  90. return str(kanban_home())
  91. except Exception:
  92. return "1"
  93. def scrub_kanban_env(env: Mapping[str, str] | MutableMapping[str, str]) -> dict[str, str]:
  94. """Remove worker identity, retaining board/location and an inherited write fence.
  95. TASK absence alone would promote a descendant to an orchestrator. The marker
  96. survives later execs, including scripts that remove TASK themselves. This is
  97. cooperative runtime scoping, not confinement of code with direct SQLite access.
  98. The marker's value is the fenced board ROOT, so the fence applies to the lineage's
  99. board and not to every Kanban DB the descendant touches: a child running a repro
  100. against a temp ``HERMES_HOME`` got a silently read-only board there. An inherited
  101. path-valued marker is kept (a grandchild that moved HERMES_HOME must not re-fence
  102. onto its scratch root and unfence the real one).
  103. """
  104. cleaned = {k: v for k, v in env.items() if k not in KANBAN_ENV_KEYS}
  105. # Only the gateway mints ``kanban`` sessions: a descendant ``hermes chat`` sending it is refused.
  106. if cleaned.get("HERMES_SESSION_SOURCE") == "kanban":
  107. del cleaned["HERMES_SESSION_SOURCE"]
  108. inherited = str(env.get(DELEGATED_CHILD_ENV_MARKER) or "")
  109. cleaned[DELEGATED_CHILD_ENV_MARKER] = inherited if inherited and inherited != "1" else _fenced_kanban_root()
  110. return cleaned
  111. def kanban_path_is_fenced(path: os.PathLike[str] | str) -> bool:
  112. """Whether Kanban mutations at *path* (a board DB or board-metadata root) are denied for this
  113. process: always for an in-process delegate child (the parent's own board); for a spawned
  114. descendant only when *path* is the dispatcher-pinned ``HERMES_KANBAN_DB`` or lies under the
  115. fenced root the marker carries. A legacy ``"1"`` marker fences everything."""
  116. if _DELEGATED_CHILD_CONTEXT.get():
  117. return True
  118. marker = os.environ.get(DELEGATED_CHILD_ENV_MARKER, "")
  119. if not marker:
  120. return False
  121. if marker == "1":
  122. return True
  123. from pathlib import Path
  124. target = Path(path).expanduser().resolve()
  125. pinned = os.environ.get("HERMES_KANBAN_DB", "").strip()
  126. if pinned and target == Path(pinned).expanduser().resolve():
  127. return True
  128. try:
  129. target.relative_to(Path(marker).expanduser().resolve())
  130. except ValueError:
  131. return False
  132. return True
  133. @overload
  134. def delegated_child_subprocess_env(env: Mapping[str, str]) -> dict[str, str]: ...
  135. @overload
  136. def delegated_child_subprocess_env(env: None = None) -> dict[str, str] | None: ...
  137. def delegated_child_subprocess_env(
  138. env: Mapping[str, str] | MutableMapping[str, str] | None = None,
  139. ) -> dict[str, str] | None:
  140. """Carry worker/delegate descendant denial across a real process spawn.
  141. Location and credentials are untouched; callers retain their existing secret policy.
  142. Dispatcher workers and supervised tool transports grant their own explicit scope.
  143. """
  144. if not (is_delegated_child_process_context() or os.environ.get("HERMES_KANBAN_TASK")
  145. or (env and (env.get("HERMES_KANBAN_TASK") or env.get(DELEGATED_CHILD_ENV_MARKER)))):
  146. return None if env is None else dict(env)
  147. return scrub_kanban_env(os.environ if env is None else env)