diff --git a/agent/delegation_context.py b/agent/delegation_context.py index fac7fb638cbe3..89b279ba67dbd 100644 --- a/agent/delegation_context.py +++ b/agent/delegation_context.py @@ -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, ...] = ( @@ -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: + 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]) + + @overload def delegated_child_subprocess_env(env: Mapping[str, str]) -> dict[str, str]: ... diff --git a/hermes_cli/kanban_db.py b/hermes_cli/kanban_db.py index 5520ded607368..2d384a488a8d8 100644 --- a/hermes_cli/kanban_db.py +++ b/hermes_cli/kanban_db.py @@ -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") @@ -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) " @@ -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 " diff --git a/hermes_cli/kanban_db_connect.py b/hermes_cli/kanban_db_connect.py index 0886ef472558e..1617cbb775ff2 100644 --- a/hermes_cli/kanban_db_connect.py +++ b/hermes_cli/kanban_db_connect.py @@ -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`` -> ``/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) + 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): @@ -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. @@ -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( diff --git a/tests/hermes_cli/test_kanban_boards.py b/tests/hermes_cli/test_kanban_boards.py index 92215d5cb96ea..4ee9d6ea9969e 100644 --- a/tests/hermes_cli/test_kanban_boards.py +++ b/tests/hermes_cli/test_kanban_boards.py @@ -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) diff --git a/tests/hermes_cli/test_kanban_core_functionality.py b/tests/hermes_cli/test_kanban_core_functionality.py index 4d314a7f72850..0147e43322bd8 100644 --- a/tests/hermes_cli/test_kanban_core_functionality.py +++ b/tests/hermes_cli/test_kanban_core_functionality.py @@ -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 diff --git a/tests/tools/test_bot_mode_dm.py b/tests/tools/test_bot_mode_dm.py index 56b1b7f8c63d3..aec612d4a1902 100644 --- a/tests/tools/test_bot_mode_dm.py +++ b/tests/tools/test_bot_mode_dm.py @@ -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 ): diff --git a/tests/tools/test_kanban_child_self_scope.py b/tests/tools/test_kanban_child_self_scope.py new file mode 100644 index 0000000000000..7596d180ad79c --- /dev/null +++ b/tests/tools/test_kanban_child_self_scope.py @@ -0,0 +1,312 @@ +"""Child self-scope write paths on a FILE-BACKED board (amended directive §6). + +The amended composition (CTO ruling t_e645df7c): the PATH FENCE decides WHERE, +the in-process context decides the blanket deny, and the parent-grant is the +sole exception to both — exactly its one task id, on the only two sanctioned +write paths (``add_comment`` / ``add_attachment``). + +Every case runs against a real file-backed temp board (``tmp_path / *.db``) — +never ``:memory:`` — because the production gate fences on the connection's +backing path and ``connect()`` resolves real paths. Exec'd-descendant cases run +in sidecar processes with a scrubbed env (``HERMES_DELEGATED_CHILD_CONTEXT`` is +popped before any hermes import); descendant markers are path-VALUED, never +``"1"``, when scoping is intended. + +Spec mapping (§6 of the amended directive; §10 of the original): + (e) granted in-process child CAN add_comment + add_attachment on exactly its + granted id (the case that failed on the pre-amendment tree). + (f) same child DENIED on a different task id and on status/claim/complete/ + link/board-metadata mutators. + (a) non-granted in-process child mutator => PermissionError; its connect() + handle is read-only (a write attempt raises). + (b) exec'd descendant with a path-valued env marker cannot write the lineage + board; (b2) nor the pinned ``HERMES_KANBAN_DB`` (sidecar subprocess). + (c) legacy ``"1"`` marker fences everything (sidecar subprocess). + (j') descendant's temp-``HERMES_HOME`` scratch board (outside the fenced + root) init + ``create_task`` stays WRITABLE — stage2 scratch-root + restoration (sidecar subprocess). + (d) grandchild holds no grant (the ContextVar dies at the process boundary). + (g) ``is_self_scoped_write`` False when ``HERMES_KANBAN_TASK`` is set in env + but no grant exists (env-spoofing resistance). + (h) a nested grant cannot widen scope past the outer id. + (i) a fenced connect() never initializes/migrates; missing schema => + PermissionError. + (k) the granted child's handle carries busy_timeout (waits on a lock). +""" +from __future__ import annotations + +import os +import subprocess +import sys +from pathlib import Path + +import pytest + +from agent.delegation_context import ( + delegated_child_context, + delegated_self_scope_grant, + is_delegated_child_in_process_context, + is_self_scoped_write, + self_scope_grant, +) +from hermes_cli import kanban_db as kb +from hermes_cli.kanban_db_connect import connect + +_LIVE_TREE = str(Path(__file__).resolve().parents[2]) + + +def _file_board(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + """A dispatcher-owned worker board backed by a real file, with own+foreign tasks.""" + db = tmp_path / "self-scope.db" + assert not str(db).startswith(":memory:") + conn = connect(db) + assert Path(str(db)).exists() + own = kb.create_task(conn, title="own") + foreign = kb.create_task(conn, title="foreign") + for tid in (own, foreign): + kb.claim_task(conn, tid) + monkeypatch.setenv("HERMES_KANBAN_DB", str(db)) + monkeypatch.setenv("HERMES_KANBAN_TASK", own) + monkeypatch.delenv("HERMES_DELEGATED_CHILD_CONTEXT", raising=False) + return conn, db, own, foreign + + +def _denied(fn) -> str: + try: + fn() + except Exception as exc: # noqa: BLE001 - the denial type is the assertion + return type(exc).__name__ + return "ok" + + +def _run_sidecar(script: str, env_extra: dict, tmp_path: Path, *, marker: str | None) -> str: + """Run a child sidecar with a scrubbed env; return its last ``OUT`` line. + + The inherited ``HERMES_DELEGATED_CHILD_CONTEXT`` is popped inside the child + before any hermes import (this host's shell exports it), then re-set to the + case's intended *marker* value — path-valued for scoped descendants, ``"1"`` + for the legacy case, never left at the ambient agent's value. + """ + env = dict(os.environ) + env.pop("HERMES_DELEGATED_CHILD_CONTEXT", None) + env.update(env_extra) + script_path = tmp_path / "_sidecar_child.py" + script_path.write_text(script, encoding="utf-8") + r = subprocess.run( + [sys.executable, str(script_path), marker or ""], + capture_output=True, text=True, env=env, timeout=120, + ) + lines = [l for l in r.stdout.splitlines() if l.startswith("OUT")] + return lines[-1] if lines else f"OUT-ERROR {r.stderr[-400:]}" + + +# --------------------------------------------------------------------------- +# In-process child cases — the gate + connect() branch run in THIS process. +# --------------------------------------------------------------------------- + +def test_e_granted_child_can_self_report_on_granted_id(tmp_path, monkeypatch): + """(e) granted in-process child CAN comment + attach on exactly its granted id.""" + conn, _db, own, _foreign = _file_board(tmp_path, monkeypatch) + with delegated_child_context("child"), delegated_self_scope_grant(own, "lock"): + assert is_delegated_child_in_process_context() + cid = kb.add_comment(conn, own, author="sub", body="child report") + assert cid > 0 + aid = kb.store_attachment_bytes(conn, own, "finding.txt", b"payload", board="default") + assert aid > 0 + assert [c.body for c in kb.list_comments(conn, own)] == ["child report"] + assert [a.filename for a in kb.list_attachments(conn, own)] == ["finding.txt"] + + +def test_f_granted_child_denied_elsewhere(tmp_path, monkeypatch): + """(f) same child DENIED on a different task id and on lifecycle mutators.""" + conn, _db, own, foreign = _file_board(tmp_path, monkeypatch) + with delegated_child_context("child"), delegated_self_scope_grant(own, "lock"): + assert _denied(lambda: kb.add_comment(conn, foreign, author="sub", body="x")) == "PermissionError" + assert _denied(lambda: kb.store_attachment_bytes( + conn, foreign, "x.txt", b"x", board="default")) == "PermissionError" + assert _denied(lambda: kb.create_task(conn, title="child-created")) == "PermissionError" + assert _denied(lambda: kb.claim_task(conn, foreign)) == "PermissionError" + assert _denied(lambda: kb.complete_task(conn, own, summary="not yours")) == "PermissionError" + assert _denied(lambda: kb.link_tasks(conn, own, foreign)) == "PermissionError" + assert _denied(lambda: kb.set_reasoning_effort(conn, own, effort="high")) == "PermissionError" + assert _denied(lambda: kb.write_board_metadata(board="default", name="x")) == "PermissionError" + assert kb.list_comments(conn, foreign) == [] + own_task = kb.get_task(conn, own) + assert own_task is not None and own_task.status == "running" + + +def test_g_env_identity_without_grant_is_not_self_scoped(tmp_path, monkeypatch): + """(g) HERMES_KANBAN_TASK in env with NO grant => is_self_scoped_write False + denied.""" + conn, _db, own, _foreign = _file_board(tmp_path, monkeypatch) + assert os.environ["HERMES_KANBAN_TASK"] == own + with delegated_child_context("child"): + assert is_self_scoped_write(own) is False + assert _denied(lambda: kb.add_comment(conn, own, author="sub", body="x")) == "PermissionError" + assert kb.list_comments(conn, own) == [] + + +def test_h_nested_grant_cannot_widen_scope(tmp_path, monkeypatch): + """(h) an inner grant for another id does not widen the outer grant's scope.""" + conn, _db, own, foreign = _file_board(tmp_path, monkeypatch) + with delegated_child_context("child"), delegated_self_scope_grant(own, "lock"): + assert is_self_scoped_write(own) is True + with delegated_self_scope_grant(foreign, "lock"): + assert is_self_scoped_write(foreign) is True + assert is_self_scoped_write(own) is False + assert _denied(lambda: kb.add_comment(conn, own, author="sub", body="x")) == "PermissionError" + assert is_self_scoped_write(own) is True + assert _denied(lambda: kb.add_comment(conn, foreign, author="sub", body="x")) == "PermissionError" + + +def test_a_non_granted_child_mutator_denied_and_handle_readonly(tmp_path, monkeypatch): + """(a) non-granted in-process child mutator => PermissionError; handle read-only.""" + conn, db, own, _foreign = _file_board(tmp_path, monkeypatch) + with delegated_child_context("child"): + assert self_scope_grant() is None + assert _denied(lambda: kb.add_comment(conn, own, author="sub", body="x")) == "PermissionError" + assert _denied(lambda: kb.create_task(conn, title="x")) == "PermissionError" + # The connect() handle itself must be read-only. + ro = connect(db) + assert _denied(lambda: ro.execute("CREATE TABLE IF NOT EXISTS zz(x)")) in ( + "OperationalError", "PermissionError", + ) + ro.close() + + +def test_k_granted_child_handle_carries_busy_timeout(tmp_path, monkeypatch): + """(k) the granted child's writable handle keeps the generous busy_timeout.""" + conn, db, own, _foreign = _file_board(tmp_path, monkeypatch) + with delegated_child_context("child"), delegated_self_scope_grant(own, "lock"): + granted_conn = connect(db) + timeout_ms = granted_conn.execute("PRAGMA busy_timeout").fetchone()[0] + assert int(timeout_ms) >= 1000 + granted_conn.close() + + +def test_i_fenced_connect_never_initializes_missing_board(tmp_path, monkeypatch): + """(i) a fenced connect() never initializes/migrates; missing schema fails closed.""" + conn, _db, own, _foreign = _file_board(tmp_path, monkeypatch) + # An EXISTING but schema-less board file: a fenced connect must neither + # create a missing file nor migrate this one — it fails closed instead. + schemaless = tmp_path / "schemaless-board.db" + schemaless.write_bytes(b"") + with delegated_child_context("child"): + assert _denied(lambda: connect(schemaless)) == "PermissionError" + assert schemaless.read_bytes() == b"" + + +# --------------------------------------------------------------------------- +# Exec'd descendant cases — sidecar processes with a scrubbed env. +# --------------------------------------------------------------------------- + +_DESCENDANT_WRITE = """\ +import os, sys +L = {live!r} +sys.path.insert(0, L) +os.environ.pop("HERMES_DELEGATED_CHILD_CONTEXT", None) +if sys.argv[1]: + os.environ["HERMES_DELEGATED_CHILD_CONTEXT"] = sys.argv[1] +from hermes_cli import kanban_db as kb +import hermes_cli.kanban_db_connect as kbc +try: + conn = kbc.connect(kbc.Path({db!r})) + kb.add_comment(conn, {task!r}, author="desc", body="should not land") + print("OUT WROTE (BAD)") +except PermissionError: + print("OUT PermissionError") +except Exception as e: + print("OUT", type(e).__name__, str(e)[:120]) +""" + +_SCRATCH_INIT = """\ +import os, sys +L = {live!r} +sys.path.insert(0, L) +os.environ.pop("HERMES_DELEGATED_CHILD_CONTEXT", None) +if sys.argv[1]: + os.environ["HERMES_DELEGATED_CHILD_CONTEXT"] = sys.argv[1] +import hermes_cli.kanban_db_connect as kbc +from hermes_cli import kanban_db as kb +try: + kbc.init_db(kbc.Path({db!r})) + conn = kbc.connect(kbc.Path({db!r})) + tid = kb.create_task(conn, title="scratch", created_by="desc") + print("OUT SCRATCH-OK", tid) +except Exception as e: + print("OUT SCRATCH-FAIL", type(e).__name__, str(e)[:120]) +""" + +_GRANDCHILD = """\ +import os, sys +L = {live!r} +sys.path.insert(0, L) +os.environ.pop("HERMES_DELEGATED_CHILD_CONTEXT", None) +if sys.argv[1]: + os.environ["HERMES_DELEGATED_CHILD_CONTEXT"] = sys.argv[1] +from agent.delegation_context import self_scope_grant +g = self_scope_grant() +print("OUT GRANT", "none" if g is None else g[0]) +""" + + +def test_b_exec_descendant_cannot_write_lineage_board(tmp_path, monkeypatch): + """(b) exec'd descendant (path-valued marker) cannot write the lineage board.""" + conn, db, own, _foreign = _file_board(tmp_path, monkeypatch) + out = _run_sidecar( + _DESCENDANT_WRITE.format(live=_LIVE_TREE, db=str(db), task=own), + {}, tmp_path, + marker=str(tmp_path), + ) + assert "PermissionError" in out, out + assert kb.list_comments(conn, own) == [] + + +def test_b2_exec_descendant_cannot_write_pinned_db(tmp_path, monkeypatch): + """(b2) ...nor the board it pins via HERMES_KANBAN_DB.""" + conn, db, own, _foreign = _file_board(tmp_path, monkeypatch) + out = _run_sidecar( + _DESCENDANT_WRITE.format(live=_LIVE_TREE, db=str(db), task=own), + {"HERMES_KANBAN_DB": str(db)}, + tmp_path, + marker=str(tmp_path), + ) + assert "PermissionError" in out, out + + +def test_c_legacy_marker_fences_everything(tmp_path, monkeypatch): + """(c) a legacy \"1\" marker fences everything, including unrelated boards.""" + conn, db, own, _foreign = _file_board(tmp_path, monkeypatch) + out = _run_sidecar( + _DESCENDANT_WRITE.format(live=_LIVE_TREE, db=str(db), task=own), + {}, tmp_path, + marker="1", + ) + assert "PermissionError" in out, out + + +def test_jp_scratch_root_board_stays_writable(tmp_path, monkeypatch): + """(j') descendant's temp-HERMES_HOME scratch board (outside the fenced root) + stays writable — init + create_task succeed (stage2 scratch-root restoration).""" + scratch_home = tmp_path / "scratch-home" + scratch_home.mkdir() + scratch_db = scratch_home / "kanban.db" + out = _run_sidecar( + _SCRATCH_INIT.format(live=_LIVE_TREE, db=str(scratch_db)), + {"HERMES_KANBAN_HOME": str(scratch_home)}, + tmp_path, + marker=str(tmp_path / "real-home"), + ) + assert "SCRATCH-OK" in out, out + assert scratch_db.exists() + + +def test_d_grandchild_holds_no_grant(tmp_path, monkeypatch): + """(d) a grandchild process holds no grant — the ContextVar dies at exec.""" + conn, db, own, _foreign = _file_board(tmp_path, monkeypatch) + out = _run_sidecar( + _GRANDCHILD.format(live=_LIVE_TREE), + {"HERMES_KANBAN_TASK": own}, + tmp_path, + marker=str(tmp_path), + ) + assert "OUT GRANT none" in out, out diff --git a/tools/bot_mode_dm.py b/tools/bot_mode_dm.py index c6aebeb9656c2..35bc15cda859a 100644 --- a/tools/bot_mode_dm.py +++ b/tools/bot_mode_dm.py @@ -22,6 +22,7 @@ import os import re import shlex +import shutil import stat import subprocess import sys @@ -408,6 +409,26 @@ def _delivery_lock(argv: list[str], *, stdin_file: bool): return acquire_turn_lock(_hermes_root(Path(_default_home())), argv[2]) +def _park_undelivered(dm_file: str, target: str) -> Optional[str]: + """Copy an undelivered DM body aside and return its path (None if it can't be saved). + + ``_run_delivery`` unlinks ``dm_file`` unconditionally, which is right for a delivered + message but destroys the only verbatim copy when the turn never ran: the sender's next + turn is a self-summary, so literal spans (quoted replacement text, code, other-language + prose) are unrecoverable and get paraphrased on resend. Parked copies age out with the + same sweep as DM payloads. + """ + try: + stamp = time.strftime("%Y%m%d-%H%M%S") + parked = _dm_dir() / f"undelivered-{target}-{stamp}-{os.getpid()}.txt" + shutil.copyfile(dm_file, parked) + parked.chmod(0o600) + return str(parked) + except OSError: + logger.debug("could not park undelivered DM body", exc_info=True) + return None + + def _run_local_turn(argv: list[str], dm_file: str, *, env: Optional[dict[str, str]] = None) -> int: """One Bot Chat turn via ``--query-file`` (plus one policy-gated retry); re-emits the transport's streams and returns its exit code. Transient failures re-run the @@ -440,10 +461,18 @@ def _turn(turn_env=env): # never ran — tell the sender plainly instead of leaking a raw lease error. # See #100523. who = argv[argv.index("-p") + 1] if "-p" in argv[:-1] else "the teammate" + # The turn never ran, so nothing on the target side ever saw this text and the + # sender's own next turn is a summary, not the payload. Park the undelivered body + # where a resend can read it verbatim instead of destroying the only literal copy. + undelivered = _park_undelivered(dm_file, who) print(json.dumps({ "error": f"Delivery failed: @{who}'s Bot Chat is open on another " - "surface right now, so your message was NOT delivered. Try again later.", + "surface right now, so your message was NOT delivered. Try again later." + + (f" Your unsent message body is preserved at {undelivered} — " + "resend it from there so verbatim content is not retyped from memory." + if undelivered else ""), "reason": "target_busy", + **({"undelivered_body_path": undelivered} if undelivered else {}), })) return 1 # Re-emit the transport's streams: stdout is the reply text the diff --git a/tools/delegate_tool_child_run.py b/tools/delegate_tool_child_run.py index 1da0c5d38e778..1772e69805536 100644 --- a/tools/delegate_tool_child_run.py +++ b/tools/delegate_tool_child_run.py @@ -853,8 +853,15 @@ def await_child(self) -> tuple[Optional[Dict[str, Any]], Optional[Dict[str, Any] def _run_with_thread_capture(): worker_thread_holder["t"] = threading.current_thread() - from agent.delegation_context import delegated_child_context - with delegated_child_context(str(getattr(child, "session_id", "") or "")): + from agent.delegation_context import ( + capture_self_scope_identity, delegated_child_context, delegated_self_scope_grant, + ) + import contextlib + + identity = capture_self_scope_identity() + grant = (delegated_self_scope_grant(*identity) if identity is not None + else contextlib.nullcontext()) + with delegated_child_context(str(getattr(child, "session_id", "") or "")), grant: return child.run_conversation( user_message=user_message, task_id=self.child_task_id, stream_callback=self.relay_text, )