Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions agent/delegation_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@
# so delegate_task-specific behaviour (subprocess env scrubbing, its error strings) is unchanged.
_NON_DISPATCHER_OWNED_CONTEXT: ContextVar[bool] = ContextVar("hermes_non_dispatcher_owned_context", default=False)

# ``(task_id, claim_lock)`` a child may self-report against — captured FROM THE PARENT at the
# moment of delegation, never read out of the child's own environment. See
# :func:`delegated_self_scope_grant`.
_SELF_SCOPE_GRANT: ContextVar["tuple[str, str | None] | None"] = ContextVar(
"hermes_delegated_self_scope_grant", default=None)

DELEGATED_CHILD_ENV_MARKER = "HERMES_DELEGATED_CHILD_CONTEXT"

KANBAN_ENV_KEYS: tuple[str, ...] = (
Expand Down Expand Up @@ -142,6 +148,69 @@ def kanban_path_is_fenced(path: "os.PathLike[str] | str") -> bool:
return True


def is_delegated_child_in_process_context() -> bool:
"""True when THIS context is an in-process ``delegate_task`` child.

ContextVar-only: never true for a spawned descendant that merely carries the
``HERMES_DELEGATED_CHILD_CONTEXT`` env marker. The mutation gate uses this to
separate the blanket in-process deny (parent's own board) from the path-scoped
fence that governs exec'd descendants.
"""
return bool(_DELEGATED_CHILD_CONTEXT.get())


@contextmanager
def delegated_self_scope_grant(task_id: str | None, claim_lock: str | None = None) -> Iterator[None]:
"""Hand a child the ONE task id it may self-report against (comment/attach).

The identity is captured by the PARENT — the dispatcher-owned worker that
still holds ``HERMES_KANBAN_TASK`` and its claim lock — and handed down as
context, never re-read from the child's own environment. ``scrub_kanban_env``
strips ``HERMES_KANBAN_TASK`` from every child env by construction, so an
env-keyed carve-out could only ever fire on an id the child supplied itself,
which is precisely the prompt-injection vector the ownership gate exists to
stop. A grant is in-process only: it does not cross ``scrub_kanban_env``, so
a subprocess descendant of the child stays fully fenced.
"""
tid = (task_id or "").strip()
token = _SELF_SCOPE_GRANT.set((tid, (claim_lock or "").strip() or None) if tid else None)
try:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 — this is not parent-only authority. A delegated child can import this same context manager and call delegated_self_scope_grant(foreign_id, ...); there is no issuer/context check before _SELF_SCOPE_GRANT.set. The new test_h_nested_grant_cannot_widen_scope even proves the dangerous intermediate state by asserting is_self_scoped_write(foreign) is True inside a nested foreign grant. From there add_comment / add_attachment accept the forged id. Install the grant only from the dispatcher-owned parent frame (before entering child context), refuse replacement from a child/already-granted scope, and add the foreign-write regression.

yield
finally:
_SELF_SCOPE_GRANT.reset(token)


def self_scope_grant() -> tuple[str, str | None] | None:
"""``(task_id, claim_lock)`` this context may self-report against, else None.

Fails closed in a subprocess: the grant is a ContextVar, so it is absent in
any spawned descendant even though the env marker survives.
"""
return _SELF_SCOPE_GRANT.get()


def capture_self_scope_identity() -> tuple[str, str | None] | None:
"""Read the dispatcher-issued identity of the CURRENT process, in the parent's frame.

Call this BEFORE entering ``delegated_child_context`` — it is only truthful
while the caller is still the dispatcher-owned worker. Returns ``None`` for a
delegated child, an in-process cron run, or a plain session, so a child that
delegates further hands its grandchild nothing.
"""
if not is_dispatcher_owned_worker_context():
return None
task_id = (os.environ.get("HERMES_KANBAN_TASK") or "").strip()
if not task_id:
return None
return task_id, (os.environ.get("HERMES_KANBAN_CLAIM_LOCK") or "").strip() or None


def is_self_scoped_write(task_id: str | None) -> bool:
"""True when ``task_id`` is exactly the dispatcher-provided grant for this context."""
grant = _SELF_SCOPE_GRANT.get()
return bool(grant and task_id and str(task_id).strip() == grant[0])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 — the captured claim generation is never validated. The grant stores (task_id, claim_lock), but this predicate checks only grant[0]; connect() likewise checks only that a grant exists. A child granted under claim L1 therefore remains able to self-report after the task is completed/reclaimed under L2. Consume the claim/run generation (and exact board identity) in the same transaction as the allowed write, with a stale-L1 → new-L2 refusal regression.



@overload
def delegated_child_subprocess_env(env: Mapping[str, str]) -> dict[str, str]: ...

Expand Down
46 changes: 39 additions & 7 deletions hermes_cli/kanban_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,18 +132,46 @@ def normalize_reasoning_effort(effort: Optional[str]) -> Optional[str]:
KANBAN_ATTACHMENT_MAX_BYTES = 25 * 1024 * 1024 # one cap for dashboard, tools and CLI


def _assert_not_delegated_child_mutation(path: "str | Path | None" = None) -> None:
def _assert_not_delegated_child_mutation(
*, path: "str | Path | None" = None, self_scoped_task: Optional[str] = None
) -> None:
"""Reject Kanban mutations from ``delegate_task`` child contexts.

The tool/CLI fast-fail guards are UX, not a trust boundary (a child can shell
out or import this module); the invariant lives here so every ``write_txn``
user and board-metadata mutator fails closed before touching durable state.
*path* is the board DB / metadata root being mutated; ``None`` means the
lineage's own board (``kanban_home()``).
*path* is the board DB / metadata root being mutated; it defaults to the
lineage's own board (``kanban_home()``) when ``None``.

``self_scoped_task`` is the ONE carve-out, and the sole exception to BOTH
the path fence and the blanket in-process deny: a child may self-report
(comment, attach) on exactly the granted id — the task the
DISPATCHER-OWNED PARENT handed it via
``agent.delegation_context.delegated_self_scope_grant`` — on the only two
sanctioned write paths. The id is never read
from the child's own environment — ``scrub_kanban_env`` strips
``HERMES_KANBAN_TASK`` by construction, so an env-keyed carve-out could only
fire on an id the child supplied itself. The grant is a ContextVar, so a
subprocess descendant (grandchild) of the child holds no grant and stays
fully fenced even though the delegated-child env marker survives the exec.
"""
from agent.delegation_context import kanban_path_is_fenced
try:
from agent.delegation_context import (
is_delegated_child_in_process_context, is_self_scoped_write, kanban_path_is_fenced,
)
from hermes_cli.kanban_db import kanban_home

if kanban_path_is_fenced(kanban_home() if path is None else path):
in_process = is_delegated_child_in_process_context()
self_scoped = bool(self_scoped_task) and is_self_scoped_write(self_scoped_task)
fenced = kanban_path_is_fenced(kanban_home() if path is None else path)
except Exception:
# Fail closed: without the real context, a present env marker denies all.
in_process = bool(os.environ.get("HERMES_DELEGATED_CHILD_CONTEXT"))
self_scoped = False
fenced = in_process
if fenced and not self_scoped:
raise PermissionError("delegate_task child contexts cannot mutate Kanban tasks or boards")
if in_process and not self_scoped:
raise PermissionError("delegate_task child contexts cannot mutate Kanban tasks or boards")


Expand Down Expand Up @@ -1768,7 +1796,10 @@ def add_comment(conn: sqlite3.Connection, task_id: str, author: str, body: str)
now = int(time.time())
# ``allow_nested=True``: graph builders (kanban_swarm blackboard seeding)
# compose comment writes under one outer commit.
with write_txn(conn, allow_nested=True):
# ``self_scoped_task``: a delegated child may comment on the task the
# dispatcher-owned parent granted it, and only that one (see
# ``_assert_not_delegated_child_mutation``).
with write_txn(conn, allow_nested=True, self_scoped_task=task_id):
_require_task(conn, task_id)
cur = conn.execute(
"INSERT INTO task_comments (task_id, author, body, created_at) "
Expand Down Expand Up @@ -1876,7 +1907,8 @@ def add_attachment(
if not stored_path or not stored_path.strip():
raise ValueError("attachment stored_path is required")
now = int(time.time())
with write_txn(conn):
# ``self_scoped_task``: the attach half of the child self-report carve-out.
with write_txn(conn, self_scoped_task=task_id):
_require_task(conn, task_id)
cur = conn.execute(
"INSERT INTO task_attachments "
Expand Down
30 changes: 23 additions & 7 deletions hermes_cli/kanban_db_connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -673,11 +673,21 @@ def connect(db_path: Optional[Path] = None, *, board: Optional[str] = None) -> s
:func:`kanban_db_path` (``HERMES_KANBAN_DB`` -> ``HERMES_KANBAN_BOARD`` ->
``<root>/kanban/current`` -> ``default``)."""
path = db_path if db_path is not None else _kb.kanban_db_path(board=board)
from agent.delegation_context import kanban_path_is_fenced
if kanban_path_is_fenced(path):
# Reads must not enter schema/backfill write transactions. Never create a
# missing board or migrate on a descendant's behalf; the owner initializes it.
conn = sqlite3.connect(path.resolve().as_uri() + "?mode=ro", uri=True)
from agent.delegation_context import (
is_delegated_child_in_process_context, kanban_path_is_fenced, self_scope_grant,
)
if not kanban_path_is_fenced(path):
pass # unfenced (owner, or descendant scratch board outside the fenced root)
else:
# Fenced: reads only, except the ONE writable case — an in-process child
# holding a dispatcher-issued grant (its own card's comment/attach rows).
# ``_sqlite_connect`` keeps busy_timeout so a concurrent parent write waits
# instead of instant-locking. Never init_db / migrations here; missing
# schema fails closed.
if is_delegated_child_in_process_context() and self_scope_grant() is not None:
conn = _sqlite_connect(path)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 — this widens two sanctioned writes into a generic writable database capability. _sqlite_connect(path) returns the child a normal writable SQLite connection. write_txn() can guard helper calls, but it cannot mediate conn.execute(...) / commit() issued directly by child code. That defeats the read-only lower boundary #69837 relied on for direct DB imports. Keep the child connection read-only and put comment/attachment writes behind a narrow gated operation (or enforce equivalent restrictions at the SQLite layer); add direct-SQL UPDATE/INSERT denial tests while a valid grant exists.

else:
conn = sqlite3.connect(path.resolve().as_uri() + "?mode=ro", uri=True)
conn.row_factory = sqlite3.Row
conn.text_factory = _kb._lossy_text
if not _schema_is_present(conn):
Expand Down Expand Up @@ -1188,7 +1198,8 @@ def _main_db_file(conn: sqlite3.Connection) -> Optional[str]:


@contextlib.contextmanager
def write_txn(conn: sqlite3.Connection, *, allow_nested: bool = False):
def write_txn(conn: sqlite3.Connection, *, allow_nested: bool = False,
self_scoped_task: str | None = None):
"""IMMEDIATE write transaction; a claim CAS inside is atomic — at most one
concurrent writer succeeds.

Expand All @@ -1197,8 +1208,13 @@ def write_txn(conn: sqlite3.Connection, *, allow_nested: bool = False):
``add_comment``) opt in — helpers with post-commit side effects
(``complete_task`` & co.) must never run under an open outer transaction,
since those side effects would fire while the outer txn can still roll back.

``self_scoped_task`` forwards the self-report carve-out to
``_assert_not_delegated_child_mutation``: only the two write paths a
delegated child may use on ITS OWN dispatcher-granted task (``add_comment``,
``add_attachment``) pass it. Every other writer keeps failing closed.
"""
_kb._assert_not_delegated_child_mutation(_main_db_file(conn))
_kb._assert_not_delegated_child_mutation(path=_main_db_file(conn), self_scoped_task=self_scoped_task)
if getattr(conn, "in_transaction", False):
if not allow_nested:
raise RuntimeError(
Expand Down
30 changes: 12 additions & 18 deletions tests/hermes_cli/test_kanban_boards.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,31 +257,25 @@ def fake_popen(cmd, *args, **kwargs):
return FakeProc()

monkeypatch.setattr(subprocess, "Popen", fake_popen)
# Hermetic w.r.t. the dispatcher's own INVOCATION_ID, and faithful
# to real dispatch: only a claimed task (which carries a run id) is
# ever spawned, so create + claim on the board instead of
# hand-building an unclaimed Task with no run id.
monkeypatch.delenv("INVOCATION_ID", raising=False)
kb.create_board("spawntest")

task = kb.Task(
id="t_abc",
title="worker test",
body=None,
assignee="teknium",
status="ready",
priority=0,
created_by="user",
created_at=0,
started_at=None,
completed_at=None,
workspace_kind="scratch",
workspace_path=None,
claim_lock=None,
claim_expires=None,
tenant=None,
)
with kbc.connect(board="spawntest") as conn:
tid = kb.create_task(
conn, title="worker test", assignee="teknium",
)
task = kb.claim_task(conn, tid)
assert task is not None and task.current_run_id is not None

kbd._default_spawn(task, str(fresh_home / "ws"), board="spawntest")

env = captured["env"]
assert env["HERMES_KANBAN_BOARD"] == "spawntest"
assert env["HERMES_KANBAN_TASK"] == "t_abc"
assert env["HERMES_KANBAN_TASK"] == tid
# DB path should match the per-board DB, not the legacy default.
expected_db = fresh_home / "kanban" / "boards" / "spawntest" / "kanban.db"
assert env["HERMES_KANBAN_DB"] == str(expected_db)
Expand Down
7 changes: 6 additions & 1 deletion tests/hermes_cli/test_kanban_core_functionality.py
Original file line number Diff line number Diff line change
Expand Up @@ -720,12 +720,17 @@ def fake_popen(cmd, **kwargs):
return FakeProc()

monkeypatch.setattr("subprocess.Popen", fake_popen)
# Hermetic w.r.t. the dispatcher's own INVOCATION_ID, and faithful to
# real dispatch: only a claimed task (which carries a run id) is ever
# spawned, so claim here instead of get_task on an unclaimed row.
monkeypatch.delenv("INVOCATION_ID", raising=False)

conn = kbc.connect()
try:
tid = kb.create_task(conn, title="skill-loading test",
assignee="some-profile")
task = kb.get_task(conn, tid)
task = kb.claim_task(conn, tid)
assert task is not None and task.current_run_id is not None
workspace = kbw.resolve_workspace(task)
pid = kbd._default_spawn(task, str(workspace))
assert pid == 99999
Expand Down
28 changes: 28 additions & 0 deletions tests/tools/test_bot_mode_dm.py
Original file line number Diff line number Diff line change
Expand Up @@ -760,6 +760,34 @@ def test_local_turn_reemits_empty_stdout_for_a_bare_silence_marker(tmp_path, cap
assert capsys.readouterr().out.strip() == prose


def test_live_owner_refusal_preserves_verbatim_body(tmp_path, capsys, monkeypatch):
"""A refused turn never ran, so the recipient never saw the text and the sender's own
next turn is only a self-summary. The body must survive the runner's unlink, or verbatim
content (quoted replacement prose, code) is unrecoverable and gets paraphrased on resend."""
monkeypatch.setattr(bot_mode_dm, "_dm_dir", lambda: tmp_path / "parked")
(tmp_path / "parked").mkdir()
verbatim = 'Remplacez par : "Ces taux s\'empilent sur votre rabais de base."'
dm_file = tmp_path / "message.txt"
dm_file.write_text(verbatim, encoding="utf-8")
child = tmp_path / "owned.py"
child.write_text(
"import sys\n"
"print('hermes-refusal-reason: SESSION_NOT_OWNED', file=sys.stderr)\n"
"raise SystemExit(1)\n",
encoding="utf-8",
)

returncode = bot_mode_dm._run_delivery(
[sys.executable, str(child), "-p", "ops"], str(dm_file), stdin_file=False
)

assert returncode == 1
payload = json.loads(capsys.readouterr().out)
parked = Path(payload["undelivered_body_path"])
assert parked.read_text(encoding="utf-8") == verbatim
assert not dm_file.exists()


def test_query_file_delivery_closes_stdin_for_initial_attempt_and_retry(
tmp_path, monkeypatch
):
Expand Down
Loading